Lin*_*son 17 python dictionary
从另一个函数,我有这样的元组('falseName', 'realName', positionOfMistake),例如.('Milter', 'Miller', 4).我需要编写一个函数来创建这样的字典:
D={realName:{falseName:[positionOfMistake], falseName:[positionOfMistake]...},
realName:{falseName:[positionOfMistake]...}...}
Run Code Online (Sandbox Code Playgroud)
该函数必须将字典和上面的元组作为参数.
我开始想这样的事情:
def addToNameDictionary(d, tup):
dictionary={}
tup=previousFunction(string)
for element in tup:
if not dictionary.has_key(element[1]):
dictionary.append(element[1])
elif:
if ...
Run Code Online (Sandbox Code Playgroud)
但它不起作用,我有点被困在这里.
awe*_*eis 16
如果仅添加新元组并且您确定内部字典中没有冲突,则可以执行以下操作:
def addNameToDictionary(d, tup):
if tup[0] not in d:
d[tup[0]] = {}
d[tup[0]][tup[1]] = [tup[2]]
Run Code Online (Sandbox Code Playgroud)
小智 10
collections.defaultdict当你构建dicts并且事先不知道你将拥有哪些键时,使用是一个很大的节省时间.
这里使用了两次:对于生成的dict,以及dict中的每个值.
import collections
def aggregate_names(errors):
result = collections.defaultdict(lambda: collections.defaultdict(list))
for real_name, false_name, location in errors:
result[real_name][false_name].append(location)
return result
Run Code Online (Sandbox Code Playgroud)
将此与您的代码结合使用:
dictionary = aggregate_names(previousFunction(string))
Run Code Online (Sandbox Code Playgroud)
或者测试:
EXAMPLES = [
('Fred', 'Frad', 123),
('Jim', 'Jam', 100),
('Fred', 'Frod', 200),
('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)
Run Code Online (Sandbox Code Playgroud)
dictionary's setdefault是一个更新现有dict条目的好方法,如果它存在,或者创建一个新条目,如果它不是一次性的:
循环风格:
# This is our sample data
data = [("Milter", "Miller", 4), ("Milter", "Miler", 4), ("Milter", "Malter", 2)]
# dictionary we want for the result
dictionary = {}
# loop that makes it work
for realName, falseName, position in data:
dictionary.setdefault(realName, {})[falseName] = position
Run Code Online (Sandbox Code Playgroud)
字典现在等于:
{'Milter': {'Malter': 2, 'Miler': 4, 'Miller': 4}}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
102297 次 |
| 最近记录: |