How to convert an array to a dictionary with Python [Application]

Overview

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.

Common examples

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'}

Practice

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']}

Conclusion

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'}]

Regression

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'}]

reference

--A special pattern in which keys and dictionaries are arranged alternately -For a list of tuples with 2 elements

Excelsior!!

Recommended Posts

How to convert an array to a dictionary with Python [Application]
How to convert a class object to a dictionary with SQLAlchemy
[Python] How to convert a 2D list to a 1D list
How to convert Python to an exe file
How to make a string into an array or an array into a string in Python
How to create a heatmap with an arbitrary domain in Python
How to read a CSV file with Python 2/3
How to make a dictionary with a hierarchical structure.
How to crop an image with Python + OpenCV
How to read an array with Python's ConfigParser
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
[Python] How to draw a line graph with Matplotlib
How to write a list / dictionary type of Python3
How to convert JSON file to CSV file with Python Pandas
How to deploy a Go application to an ECS instance
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary
[Python] How to create a 2D histogram with Matplotlib
[Python] How to draw a scatter plot with Matplotlib
What do you like about how to convert an array (list) to a string?
How to write a Python class
Python: How to use async with
How to install NPI + send a message to line with python
How to slice a block multiple array from a multiple array in Python
How to swap elements in an array in Python, and how to reverse an array.
A story about how Windows 10 users created an environment to use OpenCV3 with Python 3.5
How to transpose a 2D array using only python [Note]
Convert list to DataFrame with python
How to make a Python package (written for an intern)
How to get started with Python
[Python] How to swap array values
How to run an app built with Python + py2app built with Anaconda
How to build a python2.7 series development environment with Vagrant
How to use FTP with Python
Convert a string to an image
How to calculate date with python
[Python Kivy] How to create an exe file with pyinstaller
[Python] How to output a pandas table to an excel file
How to read an Excel file (.xlsx) with Pandas [Python]
Turn an array of strings with a for statement (Python3)
Convert to a string while outputting standard output with Python subprocess
How to batch start a python program created with Jupyter notebook
[Introduction to Python] How to split a character string with the split function
[Python 3.8 ~] How to define a recursive function smartly with a lambda expression
How to make a surveillance camera (Security Camera) with Opencv and Python
Try to extract a character string from an image with Python3
How to check the memory size of a dictionary in Python
I tried to make a 2channel post notification application with Python
[Python] Explains how to use the format function with an example
How to use an external editor for Python development with Grasshopper
[Python] How to store a csv file as one-dimensional array data
[Python] How to get a value with a key other than value with Enum
I tried to make a todo application using bottle with python
[ROS2] How to play a bag file with python format launch
How to send a request to the DMM (FANZA) API with python
[Python] How to convert db file to csv
Convert memo at once with Python 2to3
Convert Python> two value sequence to dictionary
How to add a package with PyCharm
[Python] How to make a class iterable
python3 How to install an external module
Convert Excel data to JSON with python