Home > database >  How to convert dict of dict to dict of specified format?
How to convert dict of dict to dict of specified format?

Time:10-08

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.

CodePudding user response:

use extend instead of 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.

CodePudding user response:

If you want to solve this problem with using append() function try this code:

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

CodePudding user response:

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.

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)

CodePudding user response:

The accepted answer by @Gabip correctly identifies that your only mistake was using append instead of 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: {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:

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?'}
  • Related