如何在python中重写字典以获得以下输出?

时间:2014-01-13 18:48:53

标签: python dictionary

给出一个分数列表:

scores = [(1,"abc")]  
#newdict = { } 

我需要返回一个包含分数字母的字典,以便这个assert语句返回True

for score, letters in scores:  
    for letter in letters:  
        assert score == new_dict.get(letter) 

1 个答案:

答案 0 :(得分:1)

这样做:

>>> scores = [(1,"abc")]
>>> new_dict = dict()
>>> for tup in scores:
...     for key in tup[1]:
...         new_dict.setdefault(key,tup[0])
>>> print(new_dict)
{'a': 1, 'c': 1, 'b': 1}