Various ways to create a dictionary (memories)

This time it looks easy at first glance, but it's actually deep, How to create a dictionary </ b> is described.

In this article, I will write in the following order. ・ How to create with curly braces ・ How to create with dict () ・ How to create in dictionary comprehension

How to create with curly braces

How to generate with {key: value, key: value, ...}.

d = {'k1': 1, 'k2': 2, 'k3': 3} print(d) # {'k1': 1, 'k2': 2, 'k3': 3}

The following two methods can be done from Python 3.5, and it seems that not only two but three or more can be done. Also d = {**d1, **d2, 'k5': 5} As it seems, it is possible to combine and add for cleaning. Even if you do this, d1 and d2 seem to remain the same.

d1 = {'k1': 1, 'k2': 2} d2 = {'k3': 3, 'k4': 4}

d = {**d1, **d2} print(d) # {'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4}

print(d1) # {'k1': 1, 'k2': 2}

print(d2) # {'k3': 3, 'k4': 4}

How to generate a dictionary with dict ()

It seems that a dictionary is generated by setting> dict (key = value). An example is shown below.

d = dict(k1=1, k2=2, k3=3) print(d) # {'k1': 1, 'k2': 2, 'k3': 3}

How to generate from a list of key and value combinations (tuples (key, value), etc.).

d = dict([('k1', 1), ('k2', 2), ('k3', 4)]) print(d) # {'k1': 1, 'k2': 2, 'k3': 4}

Also, if it is iterable as follows List tuples List of sets (set type) There is no problem with combinations such as.

・ List tuple d = dict((['k1', 1], ['k2', 2], ['k3', 4])) print(d) # {'k1': 1, 'k2': 2, 'k3': 4}

・ List of sets (set type) d = dict([{'k1', 1}, {'k2', 2}, {'k3', 4}]) print(d) # {1: 'k1', 2: 'k2', 'k3': 4}

Generate a dictionary from the zip function

keys = ['k1', 'k2', 'k3'] values = [1, 2, 3]

d = dict(zip(keys, values)) print(d) # {'k1': 1, 'k2': 2, 'k3': 3}

You can use the zip () function to create a dictionary from a list of keys and a list of values. Not limited to lists, tuples etc. are OK.

How to create from dictionary comprehension

{key: value for arbitrary variable name in iterable object}

l = ['Alice', 'Bob', 'Charlie']

d = {s: len(s) for s in l} print(d) # {'Alice': 5, 'Bob': 3, 'Charlie': 7}

The difference from the list comprehension is that it is enclosed in {} instead of [], and that the key and value are specified.

To create from a list of keys and values, use the zip () function as well as the constructor dict ().

keys = ['k1', 'k2', 'k3'] values = [1, 2, 3]

d = {k: v for k, v in zip(keys, values)} print(d) # {'k1': 1, 'k2': 2, 'k3': 3}

Summary

For the first time, I learned that there are so many ways to create a dictionary. It's quite interesting. See you next time.

Recommended Posts

Various ways to create a dictionary (memories)
[Python] List Comprehension Various ways to create a list
5 Ways to Create a Python Chatbot
Script to create a Mac dictionary file
Various ways to extract columns in a NumPy array
Create a dictionary in Python
Add a dictionary to MeCab
Create a nested dictionary using defaultdict
How to create a Conda package
How to create a virtual bridge
Metaclass (wip) to generate a dictionary
How to create a config file
Various ways to create an array of numbers from 1 to 10 in Python.
I tried to create a linebot (implementation)
How to create a clone from Github
How to create a git clone folder
How to create a repository from media
Create a Hatena dictionary for SKK (additional)
Various ways to destroy resources with scope
What is the fastest way to create a reverse dictionary in python?
Various ways to read the last line of a csv file in Python
Edit Excel from Python to create a PivotTable
Various ways to execute .py files on Windows
I want to easily create a Noise Model
How to create a Python virtual environment (venv)
How to create a function object from a string
[python] Create a list of various character types
I want to create a window in Python
Randomly sample MNIST data to create a dataset
How to create a JSON file in Python
How to make a dictionary with a hierarchical structure.
If you want to create a Word Cloud.
Create a command to encode / decode Splunk base64
Use click to create a sub-sub command --netsted sub-sub command -
Steps to create a Twitter bot with python
Try to create a new command on linux
How to create a shortcut command for LINUX
I want to create a plug-in type implementation
[Note] How to create a Ruby development environment
How to create a Kivy 1-line input box
How to create a multi-platform app with kivy
How to create a Rest Api in Django
Create a command to get the work log
[Note] How to create a Mac development environment
Various methods to numerically create the inverse function of a certain function Part 1 Polynomial regression
Read the Python-Markdown source: How to create a parser
Create a dataset of images to use for learning
A memo to create a virtual environment (venv) before Django
I tried to create a table only with Django
Create a function to visualize / evaluate the clustering result
How to create a submenu with the [Blender] plugin
Try to dynamically create a Checkbutton with Python's Tkinter
How to convert a class object to a dictionary with SQLAlchemy
Scraping your Qiita articles to create a word cloud
Create a plugin to run Python Doctest in Vim (2)
[Go] How to create a custom error for Sentry
How to write a list / dictionary type of Python3
How to create a local repository for Linux OS
I want to manually create a legend with matplotlib
How to create a simple TCP server / client script
[Morphological analysis] How to add a new dictionary to Mecab