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 ?
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.
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.
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))
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With