[英]Dynamically create dictionary keys where I can append additional values?
I have a dictionary that I'll be adding data to that looks like this: 我有一个字典,我将添加数据,如下所示:
mydict = {
'key1': ['First string message', 'Second string message'],
'key2': ['String message']
}
I am iterating through a json object that has two keys - key
and message
. 我正在迭代一个有两个键的json对象 -
key
和message
。 I want to add every key
into mydict
and append all message
s that have the same key
. 我想将每个
key
添加到mydict
并附加具有相同key
所有message
。
Example: 例:
[
{
'key': 'key1',
'message': 'First string message'
},
{
'key': 'key2',
'message': 'String message'
},
{
'key': 'key1',
'message': 'Second string message'
},
{
'key': 'key3',
'message': 'Brand new string message'
}
]
I am having a problem on building my dictionary dynamically though. 我在动态构建我的字典时遇到了问题。 How can I dynamically create my keys so that I can append additional strings?
如何动态创建我的密钥以便我可以附加其他字符串?
One of the ways I've tried is this: 我尝试过的方法之一是:
import json
response = [
{
'key': 'key1',
'message': 'First string message'
},
{
'key': 'key2',
'message': 'String message'
},
{
'key': 'key1',
'message': 'Second string message'
},
{
'key': 'key3',
'message': 'Brand new string message'
}
]
mydict = {}
for r in response:
mydict[r['key']] = mydict.get(r['key'], [r['message']])
print(mydict)
{'key1': ['First string message'], 'key2': ['String message'], 'key3': ['Brand new string message']}
This, obviously, fails my expected result because key1
doesn't contain both strings. 显然,这会使我的预期结果失败,因为
key1
不包含这两个字符串。
I tried this: 我试过这个:
for r in response:
mydict[r['key']] = mydict.get(r['key'], [r['message']]) + r['message']
But this fails with TypeError: can only concatenate list (not "str") to list
但是这与
TypeError: can only concatenate list (not "str") to list
失败TypeError: can only concatenate list (not "str") to list
How can I dynamically create my keys so that I can append additional strings? 如何动态创建我的密钥以便我可以附加其他字符串?
You should use either defaultdict
or setdefault
. 您应该使用
defaultdict
或setdefault
。 I prefer defaultdict
: 我更喜欢
defaultdict
:
from collections import defaultdict
response = [
{
'key': 'key1',
'message': 'First string message'
},
{
'key': 'key2',
'message': 'String message'
},
{
'key': 'key1',
'message': 'Second string message'
},
{
'key': 'key3',
'message': 'Brand new string message'
}
]
mydict = defaultdict(list)
for r in response:
mydict[r['key']].append(r['message'])
With setdefault
you can make mydict
a regular dictionary: 使用
setdefault
您可以使mydict
成为常规字典:
mydict = {}
for r in response:
mydict.setdefault(r['key'], []).append(r['message'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.