gpt4 book ai didi

python - Python中的字典字典?

转载 作者:IT老高 更新时间:2023-10-28 21:08:44 24 4
gpt4 key购买 nike

从另一个函数,我有这样的元组 ('falseName', 'realName', positionOfMistake),例如。 ('Milter', 'Miller', 4).我需要编写一个函数来制作这样的字典:

D={realName:{falseName:[positionOfMistake], falseName:[positionOfMistake]...}, 
realName:{falseName:[positionOfMistake]...}...}

该函数必须将字典和一个像上面一样的元组作为参数。

一开始我在想这样的事情:

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

但它不起作用,我有点卡在这里。

最佳答案

如果只是添加一个新的元组,并且你确定内部字典没有冲突,你可以这样做:

def addNameToDictionary(d, tup):
if tup[0] not in d:
d[tup[0]] = {}
d[tup[0]][tup[1]] = [tup[2]]

关于python - Python中的字典字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8550912/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com