Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中为以下输出重写字典?_Python_Dictionary - Fatal编程技术网

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

如何在python中为以下输出重写字典?,python,dictionary,Python,Dictionary,给出一个分数列表: scores = [(1,"abc")] #newdict = { } 我需要返回一个包含字母到分数映射的字典,以便此assert语句返回True: for score, letters in scores: for letter in letters: assert score == new_dict.get(letter) 这样做: >>> scores = [(1,"abc")] >>> n

给出一个分数列表:

scores = [(1,"abc")]  
#newdict = { } 
我需要返回一个包含字母到分数映射的字典,以便此
assert
语句返回
True

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

>>> 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}

这不是Python中字典的工作方式。您真正想要实现的是什么?旁白:请不要命名变量
dict
(或
list
str
或其他内置类型名称)。你的新名字隐藏了原意。我不完全确定你想达到什么目的。您正在尝试对字符串进行字符计数吗?尝试类似于
counts={letter:0表示“ABCDEFGHIJKLMNOPQRSTUVWXYZ”中的字母}
然后
表示输入字符串中的字母:if letter in counts:counts[letter]+=1