Python: Dictionaries and JSON

Dictionaries

Dictionary – a collection of keys and values, unordered, changeable and indexed.

>>> my_dict = {1: 'one', 2: 'two', 3: 'three'}
>>> my_dict.keys()
dict_keys([1, 2, 3])
>>> my_dict.values()
dict_values(['one', 'two', 'three'])
>>> my_dict.items()
dict_items([(1, 'one'), (2, 'two'), (3, 'three')])
>>> list(my_dict.items())
[(1, 'one'), (2, 'two'), (3, 'three')]

Dictionary comprehensions

Creating a dictionary from the list of keys with default value:

>>> my_dict = dict.fromkeys(['a','b','c'], 0)
>>> my_dict
{'a': 0, 'b': 0, 'c': 0}

Dictionary from list of keys and list of values:

>>> my_dict = {k: v for (k, v) in zip(['a', 'b', 'c'], [1, 2, 3])}
>>> my_dict
{'a': 1, 'b': 2, 'c': 3}

#zip is just creating tuples from 2 lists:
>>> my_list = [('a',1),('b',2),('c',3)]
>>> my_dict = {k: v for (k, v) in my_list}
>>> my_dict
{'a': 1, 'b': 2, 'c': 3}

get(<key>,<value if does not exist>) If we try to get value from the non-existing key, KeyError Exception will be raise. To avoid the crush because of this- use get() with 2 arguemnts:1- key we need to get/check 2 – value to return if the key does not exist:

>>> my_dict[2]
'two'
>>> my_dict[15]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 15
>>> my_dict.get(15,0)
0
>>> my_dict.get(15,"no such key")
'no such key'

setdefault(<key>, <default value>) – used if we need to set the value to the key only if the key doesn’t exist if the key is already in the dictionary. nothing will happen:

>>> my_dict
{1: 'one', 2: 'two', 3: 'three'}
>>> my_dict.setdefault(4,'four')
'four'
>>> my_dict
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
>>> my_dict.setdefault(4,'five')
'four'
>>> my_dict
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

#it is equil to the folling code:
>>> my_dict
{1: 'one', 2: 'two', 3: 'three'}
>>> if 4 not in my_dict.keys():
...     my_dict[4] = 'four'
...
>>> my_dict
{1: 'one', 2: 'two', 3: 'three', 4: 'four'}

Sorting by keys, Sorting by Values

Sorting by keys: items() returns tuples, and tuples are sorted by the first element first (keys) if equal (not for dictionary) second element – values:

>>> my_dict
{2: 'two', 1: 'one', 3: 'three'}
>>> sorted(my_dict.items())
[(1, 'one'), (2, 'two'), (3, 'three')]

Sorting by values: sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.

>>> my_dict = {3: 'b', 2: 'a', 1: 'c'}
>>> sorted(my_dict.items(), key=lambda val:val[1]) #sortby value
[(2, 'a'), (3, 'b'), (1, 'c')]

Dictionary vs If-Else

I like to use a dictionary instead of multiple if-else statements.

def func_with_if(x):
    if x == 'a':
        func_a()
    elif x == 'b':
        func_b()
    else:
        func_default()


# the same using dictionary
dict_func = {
    'a': func_a,
    'b': func_b,
}
x = 'a'
def func_with_dict(x):
    dict_func.get(x, func_default)()

Dictionaries Merge

classical solution – update() for each dict, the last update wins

>>> dict1 = {1:1,2:2,3:3}
>>> dict2 = {3:7,4:4,5:5}
>>> z={}
>>> z.update(dict1)
>>> z
{1: 1, 2: 2, 3: 3}
>>> z.update(dict2)
>>> z
{1: 1, 2: 2, 3: 7, 4: 4, 5: 5}

Dictionary unpacking for Python 3.5+, we can merge multiple dictionaries:

>>> dict1 = {1:1,2:2,3:3}
>>> dict2 = {3:7,4:4,5:5}
>>> dict3 = {6:6,7:7,8:8}
>>> z = {**dict1, **dict2, **dict3}
>>> z
{1: 1, 2: 2, 3: 7, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8}

JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format, best for storing and exchanging data. It is a text-only, can easily be sent to and from a server, and used as a data format by any programming language.

import json

The json module allows you to dump simple Python data structures into a file and load the data from that file the next time the program runs.

JSON uses name/value pairs: keys must be strings, written with double quotes:

  { "name":"John" } 

json.dump() and json.load()

Convert from Python to JSON – json.dump() : two arguments: a piece of data to store and a file object it can use to store the data.

>>> import json
>>> numbers = [1, 2, 3, 4]
>>> with open('filename.json', 'w') as f:
...     json.dump(numbers, f)

Convert from JSON to Python dictionary – json.load() : one argument – filename

>>> import json
>>> with open("filename.json") as f:
...     content = json.load(f)
>>> content
[1, 2, 3, 4]
>>> type(content)
<class 'list'>

dump() – If you want to dump the JSON into a file/socket
dumps() – If you need it as a string (for printing, parsing) – takes an object and produces a string:

>>> my_dict = {1:{1:1,2:2},2:2,3:3}
>>> print(json.dumps(my_dict, indent=4))
{
    "1": 1,
    "2": 2,
    "3": 3
}

indent – how many space

Share

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *