简体   繁体   English

如何将字典的字典转换为指定格式的字典?

[英]How to convert dict of dict to dict of specified format?

I have a dictionary of dictionaries as shown below:我有一个字典字典,如下所示:

d = {0: {1: ["hello"], 2: ["How are you"]}, 1: {1: ["!"], 2: ["?"]}}

and I would want it be in required format:我希望它采用所需格式:

result = {1:["hello", "!"], 2: ["How are you", "?"]} 

However, I get this in the following format using the code below:但是,我使用以下代码以以下格式获取此信息:

new_d = {}
for sub in d.values():
    for key, value in sub.items():
        new_d.setdefault(key, []).append(value)

The result is not of required structure and it causes a list of lists.结果不是必需的结构,它会导致列表列表。

{1: [['hello'], ['!']], 2: [['How are you'], ['?']]}

Any help here would be highly appreciated.这里的任何帮助将不胜感激。 Thanks.谢谢。

use extend instead of append :使用extend而不是append

new_d.setdefault(key, []).extend(value)

The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end of the list. extend()方法将可迭代对象(列表、元组、字符串等)的所有元素添加到列表的末尾。

If you want to solve this problem with using append() function try this code:如果您想使用append() function 解决此问题,请尝试以下代码:

new_d = {}
for sub in d.values():
    for key, value in sub.items():

        # Control key exist...
        if(key in new_d.keys()):
            
            new_d[key].append(value[0])
        else:
            new_d[key] = value

You can either use .extend(value) instead of .append(value) or you can add a basic for loop to flatten the list of all dictionary values as shown below.您可以使用.extend(value)而不是.append(value)或者您可以添加一个基本的 for 循环来展平所有字典值的列表,如下所示。

new_d = {}
for sub in d.values():
    for key, value in sub.items():
        new_d.setdefault(key, []).extend(value)


for i in range (0,len(d)):
    new_d[i+1] = [item for sublist in new_d.get(i+1) for item in sublist]
print(new_d)

The accepted answer by @Gabip correctly identifies that your only mistake was using append instead of extend . @Gabip 接受的答案正确地指出您唯一的错误是使用append而不是extend

That mistake being corrected, I'd also like to suggest a slightly different approach using dict comprehensions:该错误已得到纠正,我还想建议一种使用字典理解的稍微不同的方法:

d = {0: {1: ["hello"], 2: ["How are you"]}, 1: {1: ["!"], 2: ["?"]}}

new_d = {key: d[0].get(key, []) + d[1].get(key, []) for key in d[0]}
# {1: ['hello', '!'], 2: ['How are you', '?']}

Or a more robust version that takes keys from both d[0] and d[1], in case some keys are in d[1] but not in d[0]:或者一个更健壮的版本,它从 d[0] 和 d[1] 中获取密钥,以防某些密钥在 d[1] 中但不在 d[0] 中:

d = {0: {1: ["hello"], 2: ["How are you"]}, 1: {1: ["!"], 2: ["?"], 3: ['>>>']}}

new_d = {key: d[0].get(key, []) + d[1].get(key, []) for key in set(d[0].keys()) | set(d[1].keys())}
# {1: ['hello', '!'], 2: ['How are you', '?'], 3: ['>>>']}

Finally, this wasn't explicitly part of your question, but I suggest using str.join to join the strings:最后,这不是您问题的明确部分,但我建议使用str.join来连接字符串:

d = {0: {1: ["hello"], 2: ["How are you"]}, 1: {1: ["!"], 2: ["?"]}}

new_d = {key: ''.join(d[0].get(key, []) + d[1].get(key, [])) for key in d[0]}
# {1: 'hello!', 2: 'How are you?'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM