Bli*_*tva 1 python dictionary tuples list
所以我有一个带有键及其对应值的元组列表.我想让它显示为字典,所以我写道
def tup_to_dict (lst):
return dict(lst)
Run Code Online (Sandbox Code Playgroud)
现在,如果我的是[("A3", "green"), ("B5", "blue"), ("A3", "yellow")]
,我的输出将是:
{'B5': 'blue', 'A3': 'yellow'}
Run Code Online (Sandbox Code Playgroud)
我如何检查一个密钥是否已经分配了一个值而不是覆盖它.所以我的输出看起来像这样:
{"A3": "green", "B5": "blue"}
Run Code Online (Sandbox Code Playgroud)
谢谢!
dict
使用最后一个值,你想使用第一个值... swap'em!
return dict(reversed(lst))
Run Code Online (Sandbox Code Playgroud)