Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 795
Roxy Avatar asked Dec 31 '22 12:12

Roxy


2 Answers

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.

like image 198
Gabio Avatar answered Jan 04 '23 15:01

Gabio


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
like image 37
ultdevchar Avatar answered Jan 04 '23 17:01

ultdevchar