如何在for循环中创建嵌套字典(不使用defaultdict)?

huangapple go评论62阅读模式
英文:

How to create a nested dictionary in a for loop (not using defaultdict)?

问题

以下是您的翻译好的代码部分:

my input looks like this:

    test_file = [['ref1', 'test1', 2],
                 ['ref2', 'test1', 3],
                 ['ref3', 'test2', 4],
                 ['ref1', 'test2', 4],
                 ['ref2', 'test2', 1],
                 ['ref1', 'test1', 4],
                 ['ref1', 'test1', 5]]
And I'm trying to get a nested dictionary like this:

    desired_output = {'ref1':{'test1':[2,5,4]}, 
                      'ref1':{'test2':[4]}, 
                      'ref2':{'test1':[3]}, 
                      'ref2':{'test2':[1]}, 
                      'ref3':{'test2':[4]}}
I tried to use defaultdict by appending the values to the second key, however, I got this error:

> AttributeError: 'collections.defaultdict' object has no attribute
> 'append'

So, I tried this:

    for entry in test_file:
    	nest1 = {}
    	try:
    		nest1[entry[1]].append(entry[2])
    	except KeyError:
    		nest1[entry[1]] = [entry[2]]
    	try:
    		mynestdict[entry[0]].append(nest1)
    	except KeyError:
    		mynestdict[entry[0]] = [nest1]
    
    print(dict(mynestdict))

But I'm getting this:

    {'ref1': [{'test1': [2]}, {'test2': [4]}, {'test1': [4]}, {'test1': [5]}, 'ref2': [{'test1': [3]}, {'test2': [1]}, 'ref3': [{'test2': [4]}]}
I'm not familiar with nested dictionaries and I really would like to understand them, any suggestions?

请注意,您的期望输出是不太合理的,因为在Python中,字典中的键必须是唯一的。因此,无法使用相同的键多次。如果您希望将多个值与相同的键相关联,您可以使用列表或其他数据结构。如果您有关于嵌套字典的问题或其他需求,请随时提问。

英文:

my input looks like this:

test_file = [['ref1', 'test1', 2],
             ['ref2', 'test1', 3],
             ['ref3', 'test2', 4],
             ['ref1', 'test2', 4],
             ['ref2', 'test2', 1],
             ['ref1', 'test1', 4],
             ['ref1', 'test1', 5]]

And I'm trying to get a nested dictionary like this:

desired_output = {'ref1':{'test1':[2,5,4]}, 
                  'ref1':{'test2':[4]}, 
                  'ref2':{'test1':[3]}, 
                  'ref2':{'test2':[1]}, 
                  'ref3':{'test2':[4]}}

I tried to use defaultdict by appending the values to the second key, however, I got this error:

> AttributeError: 'collections.defaultdict' object has no attribute
> 'append'

So, I tried this:

for entry in test_file:
	nest1 = {}
	try:
		nest1[entry[1]].append(entry[2])
	except KeyError:
		nest1[entry[1]] = [entry[2]]
	try:
		mynestdict[entry[0]].append(nest1)
	except KeyError:
		mynestdict[entry[0]] = [nest1]

print(dict(mynestdict))

But I'm getting this:

{'ref1': [{'test1': [2]}, {'test2': [4]}, {'test1': [4]}, {'test1': [5]}], 
'ref2': [{'test1': [3]}, {'test2': [1]}], 
'ref3': [{'test2': [4]}]}

I'm not familiar with nested dictionaries and I really would like to understand them, any suggestions?

答案1

得分: 1

Since you're creating nested dictionaries, you need nested defaultdict().

result = defaultdict(lambda: defaultdict(list))

for key1, key2, value in test_file:
    result[key1][key2].append(value)

pprint(default_to_regular(result))
# Output:
{'ref1': {'test1': [2, 4, 5], 'test2': [4]},
 'ref2': {'test1': [3], 'test2': [1]},
 'ref3': {'test2': [4]}}

获取default_to_regular()函数,请访问 https://stackoverflow.com/questions/26496831/how-to-convert-defaultdict-of-defaultdicts-of-defaultdicts-to-dict-of-dicts-o

英文:

Since you're creating nested dictionaries, you need nested defaultdict().

result = defaultdict(lambda: defaultdict(list))

for key1, key2, value in test_file:
    result[key1][key2].append(value)

pprint(default_to_regular(result))
# Output:
{'ref1': {'test1': [2, 4, 5], 'test2': [4]},
 'ref2': {'test1': [3], 'test2': [1]},
 'ref3': {'test2': [4]}}

Get default_to_regular() from https://stackoverflow.com/questions/26496831/how-to-convert-defaultdict-of-defaultdicts-of-defaultdicts-to-dict-of-dicts-o

答案2

得分: 1

我认为你想要的输出是这样的,合并重复的键:

{'ref1': {'test1': [2, 4, 5], 'test2': [4]}, 'ref2': {'test1': [3], 'test2': [1]}, 'ref3': {'test2': [4]}}


要实现这个效果,只需检查嵌套键是否存在,如果不存在,则创建它们。你要求不使用 `collections.defaultdict`,以下是不使用它的代码:

test_file = [['ref1', 'test1', 2],
['ref2', 'test1', 3],
['ref3', 'test2', 4],
['ref1', 'test2', 4],
['ref2', 'test2', 1],
['ref1', 'test1', 4],
['ref1', 'test1', 5]]

d = {}
for el in test_file:
if el[0] not in d:
d[el[0]] = {}
if el[1] not in d[el[0]]:
d[el[0]][el[1]] = []

d[el[0]][el[1]].append(el[2])

print(d)


<details>
<summary>英文:</summary>

I think the output you&#39;re looking for is this, combining the duplicate keys:

{'ref1': {'test1': [2, 4, 5], 'test2': [4]}, 'ref2': {'test1': [3], 'test2': [1]}, 'ref3': {'test2': [4]}}


To get that, just check if the nested keys exist, and if they don&#39;t, then create them. You asked for code that doesn&#39;t use `collections.defaultdict` and it doesn&#39;t make it too much more:

test_file = [['ref1', 'test1', 2],
['ref2', 'test1', 3],
['ref3', 'test2', 4],
['ref1', 'test2', 4],
['ref2', 'test2', 1],
['ref1', 'test1', 4],
['ref1', 'test1', 5]]

d = {}
for el in test_file:
if el[0] not in d:
d[el[0]] = {}
if el[1] not in d[el[0]]:
d[el[0]][el[1]] = []

d[el[0]][el[1]].append(el[2])

print(d)


</details>



# 答案3
**得分**: 1

I understand your request. Here's the translated code portion:

```python
test_file = [['ref1', 'test1', 2],
             ['ref2', 'test1', 3],
             ['ref3', 'test2', 4],
             ['ref1', 'test2', 4],
             ['ref2', 'test2', 1],
             ['ref1', 'test1', 4],
             ['ref1', 'test1', 5]]

df = pd.DataFrame(test_file)

df.groupby([0, 1])[2].apply(np.array).unstack().agg(lambda x: x.dropna().to_dict(), axis=1).to_json()

Please note that this code translates the given data into a JSON format.

英文:
test_file = [[&#39;ref1&#39;, &#39;test1&#39;, 2],
             [&#39;ref2&#39;, &#39;test1&#39;, 3],
             [&#39;ref3&#39;, &#39;test2&#39;, 4],
             [&#39;ref1&#39;, &#39;test2&#39;, 4],
             [&#39;ref2&#39;, &#39;test2&#39;, 1],
             [&#39;ref1&#39;, &#39;test1&#39;, 4],
             [&#39;ref1&#39;, &#39;test1&#39;, 5]]


df = pd.DataFrame(test_file)


df.groupby([0, 1])[2].apply(np.array).unstack().agg(lambda x: x.dropna().to_dict(), axis=1).to_json()


&#39;{&quot;ref1&quot;:{&quot;test1&quot;:[2,4,5],&quot;test2&quot;:[4]},&quot;ref2&quot;:{&quot;test1&quot;:[3],&quot;test2&quot;:[1]},&quot;ref3&quot;:{&quot;test2&quot;:[4]}}&#39;

huangapple
  • 本文由 发表于 2023年4月1日 01:08:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75901065.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定