Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.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
到嵌套dict的元组的Python列表_Python_Dictionary - Fatal编程技术网

到嵌套dict的元组的Python列表

到嵌套dict的元组的Python列表,python,dictionary,Python,Dictionary,我的数据结构如下: [(a,x1,1),(a,x2,5),(b,x1,1) ...] 我想把它变成这种形式的嵌套字典 {a:{x1:1, x2:5}, b:{x1:1}...} 我试过了 dictdata = {} for row in rows: ean = row[1].encode('ascii','ignore') period = str(row[0]) value = row[2] dictdata[ean]={} # init sub dicti

我的数据结构如下:

[(a,x1,1),(a,x2,5),(b,x1,1) ...]
我想把它变成这种形式的嵌套字典

{a:{x1:1, x2:5}, b:{x1:1}...}
我试过了

dictdata = {}
for row in rows:
    ean = row[1].encode('ascii','ignore')
    period = str(row[0])
    value = row[2]
    dictdata[ean]={} # init sub dictionary
    dictdata[ean][period] = value
但是每次我执行dictdata[ean]={}时,内容都会被擦除,所以这不起作用。如果我不初始化子字典,我也无法让它工作


感谢您的任何帮助

您只需一句话就可以做到

rows = [('a','x1',1),('a','x2',5),('b','x1',1)]
result = dict()
for key1, key2, value in rows:
  result.setdefault(key1, {}).update({key2: value})

你可以用一句话来表达

rows = [('a','x1',1),('a','x2',5),('b','x1',1)]
result = dict()
for key1, key2, value in rows:
  result.setdefault(key1, {}).update({key2: value})

同样的事情,但是使用defaultdict

from collections import defaultdict
rows = [("a", "x1", 1), ("a", "x2", 5), ("b", "x1", 1)]

d = defaultdict(dict)
for k, v, v2 in rows:
    d[k][v] = v2

同样的事情,但是使用defaultdict

from collections import defaultdict
rows = [("a", "x1", 1), ("a", "x2", 5), ("b", "x1", 1)]

d = defaultdict(dict)
for k, v, v2 in rows:
    d[k][v] = v2

这就是collections.defaultdict所要解决的问题:

返回

{'a': {'x2': 5, 'x1': 1}, 'b': {'x1': 1}}

这就是collections.defaultdict所要解决的问题:

返回

{'a': {'x2': 5, 'x1': 1}, 'b': {'x1': 1}}

作为对代码的修复,正确的方法是,如果您已经创建了字典,则始终创建字典,如果没有,则实例化字典,如下所示:

>>> l
[('a', 'x1', 1), ('a', 'x2', 5), ('b', 'x1', 1)]
>>> d = {}
>>> for row in l:
        ean = row[1].encode('ascii','ignore')
        period = str(row[0])
        value = row[2]
        if period not in d:
            d[period] = {}
        if ean not in d[period]:
            d[period][ean] = {}
        d[period][ean] = value


>>> d
{'a': {b'x1': 1, b'x2': 5}, 'b': {b'x1': 1}}
您也可以直接使用“收藏”中的:

>>> l = [('a','x1',1),('a','x2',5),('b','x1',1)]
>>>
>>> from collections import defaultdict
>>> 
>>> 
>>> d = defaultdict(dict)
>>> 
>>> for k, k_sub, v in l:
        d[k][k_sub] = v

>>> d
defaultdict(<class 'dict'>, {'a': {'x1': 1, 'x2': 5}, 'b': {'x1': 1}})
>>l=[('a','x1',1),('a','x2',5),('b','x1',1)]
>>>
>>>从集合导入defaultdict
>>> 
>>> 
>>>d=默认dict(dict)
>>> 
>>>对于k,k_sub,l中的v:
d[k][k_sub]=v
>>>d
defaultdict(,{'a':{'x1':1,'x2':5},'b':{'x1':1})

作为对代码的修复,正确的方法是,如果已经创建了字典,则始终使用,如果没有,则实例化一个字典,如下所示:

>>> l
[('a', 'x1', 1), ('a', 'x2', 5), ('b', 'x1', 1)]
>>> d = {}
>>> for row in l:
        ean = row[1].encode('ascii','ignore')
        period = str(row[0])
        value = row[2]
        if period not in d:
            d[period] = {}
        if ean not in d[period]:
            d[period][ean] = {}
        d[period][ean] = value


>>> d
{'a': {b'x1': 1, b'x2': 5}, 'b': {b'x1': 1}}
您也可以直接使用“收藏”中的:

>>> l = [('a','x1',1),('a','x2',5),('b','x1',1)]
>>>
>>> from collections import defaultdict
>>> 
>>> 
>>> d = defaultdict(dict)
>>> 
>>> for k, k_sub, v in l:
        d[k][k_sub] = v

>>> d
defaultdict(<class 'dict'>, {'a': {'x1': 1, 'x2': 5}, 'b': {'x1': 1}})
>>l=[('a','x1',1),('a','x2',5),('b','x1',1)]
>>>
>>>从集合导入defaultdict
>>> 
>>> 
>>>d=默认dict(dict)
>>> 
>>>对于k,k_sub,l中的v:
d[k][k_sub]=v
>>>d
defaultdict(,{'a':{'x1':1,'x2':5},'b':{'x1':1})

如果ean不在dictdata中:dictdata[ean]={}
如果ean不在dictdata中:dictdata[ean]={}
?虽然所有解决方案都很好,但我欣赏这一方案的简单性虽然所有解决方案都很好,但我欣赏这一方案的简单性