Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a dictionary of dictionaries with multiple lists

There is one index list which will be the key of the parent dictionary:

index = [1,2,3]

and then multiple lists of which will be the child dicts:

triangles = [4,5,6]
circles = [7,8,9]
squares = [10,11,12]

the sequential elements being the data, resulting in:

{1:{'triangles':4, 'circles':7, 'squares': 10},
 2: {'triangles': 5, 'circles': 8, 'squares': 11},
 3: {'triangles': 6, 'circles': 9, 'squares': 12}}

how can I do this ?

Do you think easier to do in pandas ?

like image 523
David Hancock Avatar asked Jun 14 '17 06:06

David Hancock


People also ask

Can you put a list into a dictionary?

To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.

Can dictionaries have multiple data types?

One can only put one type of object into a dictionary. If one wants to put a variety of types of data into the same dictionary, e.g. for configuration information or other common data stores, the superclass of all possible held data types must be used to define the dictionary.


2 Answers

You can zip the lists, create the subdicts and then zip the subdicts with the indices. No restrictions on the indices; they can be non-sequencial/non-numerical:

dct =  dict(zip(index, ({'triangles': i, 'circles': j, 'squares': k} 
                          for i,j,k in zip(triangles, circles, squares))))
print(dct)

{1: {'circles': 7, 'squares': 10, 'triangles': 4},
 2: {'circles': 8, 'squares': 11, 'triangles': 5},
 3: {'circles': 9, 'squares': 12, 'triangles': 6}}

On another note, if you only need sequential counts, the index list can be replaced with enumerate:

dct =  dict(enumerate(({'triangles': i, 'circles': j, 'squares': k} 
                          for i,j,k in zip(triangles, circles, squares)), 1))
like image 141
Moses Koledoye Avatar answered Nov 14 '22 23:11

Moses Koledoye


Dict comprehnesions to the rescue!
Note, BTW, that the indices stored in index seem to be one-based although python lists are zero-based:

result =  {i : {'triangles' : triangles[i-1], 'circles' : circles[i-1], 'squares' : squares[i-1]} for i in index}
like image 43
Mureinik Avatar answered Nov 14 '22 22:11

Mureinik