I browsed about 10 sites on how to convert an array to a dictionary with Python. I found a "pattern that is not posted on the common introductory commentary blog", so I will introduce it as an advanced version.
If you search by converting from an array to a dictionary, you will find many examples with 1: 1 keys and values.
test002.py
key2=["name","age","kind"]
data2=["siva",4,"dog"]
print(dict(zip(key2,data2)))
The keys and values were in separate arrays, but I was able to convert them nicely into a dictionary.
output
{'name': 'siva', 'age': 4, 'kind': 'dog'}
In reality, it may process the following complex data. Even if you apply the common example as it is, it cannot be converted to the desired format.
test001.py
key1=["name","age","kind"]
data1=[["garm",4,"dog"],["chapalu",3,"cat"],["echidna",10,"snake"],["phoenix",6,"bird"]]
print(dict(zip(key1,data1)))
This is a mess. The data has become useless.
output
{'name': ['garm', 4, 'dog'], 'age': ['chapalu', 3, 'cat'], 'kind': ['echidna', 10, 'snake']}
Therefore, let's use the inclusion notation as follows.
test001.py
key1=["name","age","kind"]
data1=[["garm",4,"dog"],["chapalu",3,"cat"],["echidna",10,"snake"],["phoenix",6,"bird"]]
print([dict(zip(key1,item)) for item in data1])
It went well.
output
[{'name': 'garm', 'age': 4, 'kind': 'dog'}, {'name': 'chapalu', 'age': 3, 'kind': 'cat'}, {'name': 'echidna', 'age': 10, 'kind': 'snake'}, {'name': 'phoenix', 'age': 6, 'kind': 'bird'}]
When I rewrite it with a For statement, it looks like this.
test001.py
key1=["name","age","kind"]
data1=[["garm",4,"dog"],["chapalu",3,"cat"],["echidna",10,"snake"],["phoenix",6,"bird"]]
mydata = []
for item in data1:
mydata.append(dict(zip(key1,item)))
print(mydata)
The result is the same.
output
[{'name': 'garm', 'age': 4, 'kind': 'dog'}, {'name': 'chapalu', 'age': 3, 'kind': 'cat'}, {'name': 'echidna', 'age': 10, 'kind': 'snake'}, {'name': 'phoenix', 'age': 6, 'kind': 'bird'}]
--A special pattern in which keys and dictionaries are arranged alternately -For a list of tuples with 2 elements
Excelsior!!
Recommended Posts