英文:
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'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't, then create them. You asked for code that doesn't use `collections.defaultdict` and it doesn'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 = [['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()
'{"ref1":{"test1":[2,4,5],"test2":[4]},"ref2":{"test1":[3],"test2":[1]},"ref3":{"test2":[4]}}'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论