Home > Enterprise >  How do I access only the first key in a Dictionary containing 2 keys?
How do I access only the first key in a Dictionary containing 2 keys?

Time:10-19

I have a dictionary with 2 keys for each distinct value. I need to get a list of only the first key - {'Stuck', 'on', 'problem'}.

test_dict = {('Stuck','a') : 1, ('on', 'b') : 2, ('problem','c') : 3}

I've some indexing but nothing seems to work. Also did not find any. specific solution to this online.

CodePudding user response:

You don't have two keys for each distinct value: you have one key for each distinct value, but the key happens to be a tuple. If you want the first value from each tuple, then you need to:

  1. Iterate over the keys, and
  2. Extract the first value from each key
test_dict = {('Stuck','a') : 1, ('on', 'b') : 2, ('problem','c') : 3}

answer = []
for key in test_dict.keys():
    answer.append(key[0])

print(answer)

Or in a more compact form using a list comprehension:

test_dict = {('Stuck','a') : 1, ('on', 'b') : 2, ('problem','c') : 3}
answer = [key[0] for key in test_dict.keys()]
print(answer)

CodePudding user response:

Thank you for this. I also found another way using un(zip). The order is not preserved but that is not a concern for me.

test_dict = {('Stuck','a') : 1, ('on', 'b') : 2, ('problem','c') : 3}

(p, q) = zip(*set(test_dict)) print(list(p))

  • Related