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:
- Iterate over the keys, and
- 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))