简体   繁体   中英

How to create a dictionary from a list of tuples without overwriting the first unique key value?

So I've got a list of tuples with a key and its corresponding value. I wanted to have it be displayed as a dictionary, so I wrote

def tup_to_dict (lst):
    return dict(lst)

Now if my lst was [("A3", "green"), ("B5", "blue"), ("A3", "yellow")] , my output would then be:

{'B5': 'blue', 'A3': 'yellow'}

How would I go about checking if a key was already assigned a value and not overwriting it if it was. So that my output would look like this:

{"A3": "green", "B5": "blue"}

Thanks!

dict使用最后一个值,您想使用第一个值…交换它们!

return dict(reversed(lst))

This also works:

a = [("A3", "green"), ("B5", "blue"), ("A3", "yellow")]
b = dict((x,y) for x,y in reversed(a))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM