简体   繁体   English

动态创建字典键,我可以附加其他值?

[英]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对象 - keymessage 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 . 您应该使用defaultdictsetdefault 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.

相关问题 如何从无序列表创建字典,其中列表包含键,然后是多个值? - How can I create a dictionary from an unordered list, where the list contains the keys which are then followed by multiple values? 我如何从一个列表中创建一个字典,其中键是索引,值是列表的一个一个的实际元素? - How can I create a dictionary from a list where the keys are the indexes and the values are the actual elements of the list one by one? 创建字典,其中值是转换为字符串的键 - Create dictionary where values are keys transformed to strings 如何创建具有 2 个键的字典,其中第一个键是索引,第二个键来自列表,值来自 df 的列? - How can I create a dictionary with 2 keys where the the first key is the index, the second key is from a list and the values from columns of a df? 为什么我无法在此嵌套词典中创建其他键? - Why am I unable to create additional keys in this nested dictionary? 如何使用 while 循环从用户输入中附加具有任意数量的键和多个值的字典 - How can I use a while loop to append a dictionary with an arbitrary number of keys and multiple values from user inputs 将值附加到python字典中的键 - Append values to keys in python dictionary 根据键将值附加到字典 - Append values to dictionary based on keys 如何将 append 附加字典添加到我的 model_list? - How can I append additional dictionary to my model_list? 我可以从字典键数组创建字典值的 numpy 数组吗? - Can I create a numpy array of dictionary values from an array of dictionary keys?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM