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

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

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

问题

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

  1. my input looks like this:
  2. test_file = [['ref1', 'test1', 2],
  3. ['ref2', 'test1', 3],
  4. ['ref3', 'test2', 4],
  5. ['ref1', 'test2', 4],
  6. ['ref2', 'test2', 1],
  7. ['ref1', 'test1', 4],
  8. ['ref1', 'test1', 5]]
  9. And I'm trying to get a nested dictionary like this:
  10. desired_output = {'ref1':{'test1':[2,5,4]},
  11. 'ref1':{'test2':[4]},
  12. 'ref2':{'test1':[3]},
  13. 'ref2':{'test2':[1]},
  14. 'ref3':{'test2':[4]}}
  15. I tried to use defaultdict by appending the values to the second key, however, I got this error:
  16. > AttributeError: 'collections.defaultdict' object has no attribute
  17. > 'append'
  18. So, I tried this:
  19. for entry in test_file:
  20. nest1 = {}
  21. try:
  22. nest1[entry[1]].append(entry[2])
  23. except KeyError:
  24. nest1[entry[1]] = [entry[2]]
  25. try:
  26. mynestdict[entry[0]].append(nest1)
  27. except KeyError:
  28. mynestdict[entry[0]] = [nest1]
  29. print(dict(mynestdict))
  30. But I'm getting this:
  31. {'ref1': [{'test1': [2]}, {'test2': [4]}, {'test1': [4]}, {'test1': [5]}, 'ref2': [{'test1': [3]}, {'test2': [1]}, 'ref3': [{'test2': [4]}]}
  32. I'm not familiar with nested dictionaries and I really would like to understand them, any suggestions?

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

英文:

my input looks like this:

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

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

  1. desired_output = {'ref1':{'test1':[2,5,4]},
  2. 'ref1':{'test2':[4]},
  3. 'ref2':{'test1':[3]},
  4. 'ref2':{'test2':[1]},
  5. '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:

  1. for entry in test_file:
  2. nest1 = {}
  3. try:
  4. nest1[entry[1]].append(entry[2])
  5. except KeyError:
  6. nest1[entry[1]] = [entry[2]]
  7. try:
  8. mynestdict[entry[0]].append(nest1)
  9. except KeyError:
  10. mynestdict[entry[0]] = [nest1]
  11. print(dict(mynestdict))

But I'm getting this:

  1. {'ref1': [{'test1': [2]}, {'test2': [4]}, {'test1': [4]}, {'test1': [5]}],
  2. 'ref2': [{'test1': [3]}, {'test2': [1]}],
  3. '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().

  1. result = defaultdict(lambda: defaultdict(list))
  2. for key1, key2, value in test_file:
  3. result[key1][key2].append(value)
  4. pprint(default_to_regular(result))
  5. # Output:
  6. {'ref1': {'test1': [2, 4, 5], 'test2': [4]},
  7. 'ref2': {'test1': [3], 'test2': [1]},
  8. '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().

  1. result = defaultdict(lambda: defaultdict(list))
  2. for key1, key2, value in test_file:
  3. result[key1][key2].append(value)
  4. pprint(default_to_regular(result))
  5. # Output:
  6. {'ref1': {'test1': [2, 4, 5], 'test2': [4]},
  7. 'ref2': {'test1': [3], 'test2': [1]},
  8. '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

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

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

  1. 要实现这个效果,只需检查嵌套键是否存在,如果不存在,则创建它们。你要求不使用 `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]] = []

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

print(d)

  1. <details>
  2. <summary>英文:</summary>
  3. 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]}}

  1. 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]] = []

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

print(d)

  1. </details>
  2. # 答案3
  3. **得分**: 1
  4. I understand your request. Here's the translated code portion:
  5. ```python
  6. test_file = [['ref1', 'test1', 2],
  7. ['ref2', 'test1', 3],
  8. ['ref3', 'test2', 4],
  9. ['ref1', 'test2', 4],
  10. ['ref2', 'test2', 1],
  11. ['ref1', 'test1', 4],
  12. ['ref1', 'test1', 5]]
  13. df = pd.DataFrame(test_file)
  14. 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.

英文:
  1. test_file = [[&#39;ref1&#39;, &#39;test1&#39;, 2],
  2. [&#39;ref2&#39;, &#39;test1&#39;, 3],
  3. [&#39;ref3&#39;, &#39;test2&#39;, 4],
  4. [&#39;ref1&#39;, &#39;test2&#39;, 4],
  5. [&#39;ref2&#39;, &#39;test2&#39;, 1],
  6. [&#39;ref1&#39;, &#39;test1&#39;, 4],
  7. [&#39;ref1&#39;, &#39;test1&#39;, 5]]
  8. df = pd.DataFrame(test_file)
  9. df.groupby([0, 1])[2].apply(np.array).unstack().agg(lambda x: x.dropna().to_dict(), axis=1).to_json()
  10. &#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:

确定