填充嵌套字典 [英] Populating a Nested Dictionary

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

问题描述

我有一长串的嵌套元组,这些嵌套元组要遍历并以某种方式附加,以使一个空的字典:

I have a long list of nested tuples that I am iterating through and appending in a certain way such that an empty dictionary:

dict = {}

将这样填充:

dict = {a: {b:1,5,9,2,3}, b: {c:7,4,5,6,2,4}, c: {b:3,13,2,4,2}... }

该迭代将检查嵌套字典是否存在,如果存在,则将附加值,否则,创建嵌套字典.我的糟糕尝试看起来像这样:

The iteration will check if a nested dictionary exists, and if so, then it will append the value, otherwise, create a nested dictionary. My poor attempt looks something like this:

longlist = [(1,(a,b)),(2,(b,c)), (3,(c,b)) ... ]
dict = {}
    for each in longlist:
        if dict[each[1][0]][each[1][1]]:
            dict[each[1][0]][each[1][1]].append(each[0])
        else:
            dict[each[1][0]] = {}
            dict[each[1][0]][each[1][1]] = each[0]

我的方法的问题是,由于字典开头是空的,或者字典中不存在嵌套的父级,因此迭代失败.对我来说,这变得越来越复杂.我无法在网上找到太多有关如何处理嵌套词典的信息,因此我认为可以在这里提问.

The problem with my approach is that the iteration fails because the dictionary is empty to begin with or that the parent of the nest doesn't exist in dict. It's getting complicated for me. I wasn't able to find much info online on how to tackle nested dictionaries, so I thought it should be okay to ask here.

推荐答案

以下是使用collections.defaultdict

import random
import collections
choices = ['a', 'b', 'c', 'd', 'e', 'f']

longlist = []
for i in range(1, 101):
    longlist.append((i, tuple(random.sample(choices, 2))))

print longlist

final = collections.defaultdict(lambda: collections.defaultdict(list))

for value, (key1, key2) in longlist:
    final[key1][key2].append(value)


print final

通常,我更改代码的方式是首先确保嵌套字典存在(collections.defaultdict为您处理),然后始终追加一次.

In general, the way that I would change your code would be to first ensure the nested dictionaries exist (collections.defaultdict takes care of this for you) and then always append once.

类似

for value (key1, key2) in longlist:
    if not your_dict.get(key1):
        your_dict[key1] = {}
    if not your_dict.get(key1).get(key2):
        your_dict[key1][key2] = []
    your_dict[key1][key2].append(value)

也不是for行vs"for each ...".这是在迭代器中解包项目.您也可以做到

Also not the for line vs "for each ..." This is unpacking the items in the iterable. You could also have done

for value, keys in longlist:

但是由于键也是可迭代的,因此如果将其包装在括号中,也可以将其解压缩.

but since keys is an iterable as well, you can unpack it as well if you wrap it in parens.

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

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