Python中的字典词典? [英] Dictionary of dictionaries in Python?

查看:87
本文介绍了Python中的字典词典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从另一个函数来看,我有类似('falseName', 'realName', positionOfMistake)这样的元组. ('Milter', 'Miller', 4). 我需要编写一个使字典像这样的函数:

From another function, I have tuples like this ('falseName', 'realName', positionOfMistake), eg. ('Milter', 'Miller', 4). I need to write a function that make a dictionary like this:

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

该函数必须将字典和上述的元组作为参数.

The function has to take a dictionary and a tuple like above, as arguments.

我从一开始就在考虑这样的事情:

I was thinking something like this for a start:

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

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

But it is not working and I am kind of stucked here.

推荐答案

如果只是添加一个新的元组,并且您确定内部字典中没有冲突,则可以执行以下操作:

If it is only to add a new tuple and you are sure that there is no collisions in the inner dictionary you can do this:

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

这篇关于Python中的字典词典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆