Python Dictionaries #
<variable> = {'<key1>': '<value1>', '<key2>': '<value2>'}
Values can be anything really.
Select by key #
<variable>['<key>']
get() method #
Return a value from a key based on the specified dictionary
example = {
"a":"apple",
"b":"banana"
}
example.get("a")
# "apple"
If the key doesn’t exist, get()
returns None
.
To specify a different default value:
example.get("a", "Some alternative string")
Assign value #
<variable>['key'] = '<value>'
The update()
method can replace or create multiple key-value pairs.
<variable>.update({'<key1>': '<value1>', '<key2>': '<value2>'})
Delete #
del <variable>['<key>']
Or pop()
, which deletes and also returns value.
<variable>.pop('<key>')
Check if a key exists #
Returns True or False
'<some key>' in <variable>.keys()
Show the values #
<variable>.values()
Show keys and values #
print(<variable>.items())
Show all:
for key, value in <variable>.items():
print(key, value)
Update #
Add elements to dictionaries.
dict1.update({"<key>":"value"})
List of dictionaries #
It’s pretty common to have a list full of dictionaries.
Covert list of dictionaries to Pandas dataframe #
import pandas as pd
df = pd.DataFrame(<list_of_dictionaries>)