Python dictionary

I often forget about it when I say AtCoder etc., but I wrote it myself because there were few sites that were unexpectedly organized.

Declaration

Common guy

d = {}
 #Or
d = dict()

Element update

Both behaviors differ depending on the presence or absence of existing keys

d['key'] = 'value'
 #Compile error if the specified key does not exist
 #Update existing value if the specified key already exists


d.setdefault('key', 'value') 
 #If the specified key does not exist, add a new element
 #No change if the specified key already exists

Concatenation of dictionaries

As written below

d1 = {'key1': 'value1', 'key2': 'value2'}
d2 = {'key3': 'value3', 'key4': 'value4'}

d1.update(d2)
print(d1) 
 #{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'}

Get all keys and values included

Since it returns in a mysterious format, it is necessary to convert it to list type with list comprehension notation or map

d = {'key1': 'value1', 'key2': 'value2'}

[i for i in d.keys()] #['key1', 'key2']
[i for i in d.values()] #['value1', 'value2']

I'm sleepy

Recommended Posts

Python dictionary
[Python] dictionary
Python dictionary
[Python] Memo dictionary
[Python] Dictionary (hash)
Python basics: dictionary
Python3 List / dictionary memo
Python Dictionary Beginner's Guide
Python list, for statement, dictionary
Create a dictionary in Python
Avoid KeyError in python dictionary
Python> dictionary> get ()> optional value
kafka python
Python basics ⑤
python + lottery 6
Python Summary
Python comprehension
Python technique
Studying python
Notes on Python and dictionary types
Python memorandum
Python FlowFishMaster
Python service
python tips
python function ①
Python basics
Python memo
ufo-> python (3)
Expansion by argument of python dictionary
Python comprehension
Replace dictionary value with Python> update ()
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Python increment
atCoder 173 Python
Python for super beginners Python # dictionary type 1 for super beginners
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Try python
Python memo
Python iterative
Python algorithm
Python2 + word2vec
Dictionary type 2
[Python] Variables
Python sys.intern ()
Python tutorial
Python decimals
python underscore
Python summary
Start python
Dictionary type 1
Note: Python
Python basics ③
python log