DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on • Edited on

Dictionary in Python (2)

Buy Me a Coffee

*Memo:

  • My post explains a dictionary (1).
  • My post explains dictionary functions (1).
  • My post explains dictionary functions (2).

dict() can create a dictionary with dict, keyword arguments(kwargs) and a 2D iterable(list, tuple, set, frozenset and iterator) as shown below:

*Memo:

  • The 1st argument is mapping or iterable(Optional-Type:Mapping or Iterable):
    • Don't use mapping= or iterable=.
  • The 2nd arguments are **kwargs(Optional-Default:{}-Type:Any):
    • Don't use any keywords like **kwargs=, kwargs=, etc.
# Empty dict print(dict()) print(dict({})) # {}  print(dict({'name':'John', 'age':36})) # dict print(dict([('name', 'John'), ('age', 36)])) # list(tuple) print(dict(name='John', age=36)) # kwargs print(dict({'name':'John'}, age=36)) # dict & kwargs print(dict([('name', 'John')], age=36)) # list(tuple) & kwargs print(dict([['name', 'John'], ['age', 36]])) # list(list) print(dict((('name', 'John'), ('age', 36)))) # tuple(tuple) print(dict({frozenset({'name', 'John'}), # frozenset(set) frozenset({'age', 36})})) print(dict(iter([iter(['name', 'John']), # iter(iter)  iter(['age', 36])]))) # {'name': 'John', 'age': 36}  print(dict({frozenset({'name', 'John'}), # set(frozenset)  frozenset({'age', 36})})) # {'John': 'name', 36: 'age'} 
Enter fullscreen mode Exit fullscreen mode

dict() can also create a dictionary with an empty 1D iterable as shown below:

print(dict([])) # list print(dict(())) # tuple print(dict(set())) # set print(dict(frozenset(set()))) # frozenset print(dict({})) # dict print(dict(iter([]))) # iterator print(dict('')) # str print(dict(b'')) # bytes print(dict(bytearray(b''))) # bytearray print(dict(range(0))) # range # {} 
Enter fullscreen mode Exit fullscreen mode

dict() cannot create a dictionary with only one unempty iterable except dict as shown below:

print(dict({'name':'John', 'age':36})) # dict # {'name': 'John', 'age': 36}  print(dict(['A', 'B', 'C'])) # list print(dict(('A', 'B', 'C'))) # tuple print(dict({'A', 'B', 'C'})) # set print(dict(frozenset({'A', 'B', 'C'}))) # frozenset print(dict(iter(['A', 'B', 'C']))) # iterator print(dict('Hello World')) # str # ValueError: dictionary update sequence element #0 has length 1; 2 is required  print(dict(b'Hello World')) # bytes print(dict(bytearray(b'Hello World'))) # bytearray print(dict(range(100))) # range # TypeError: cannot convert dictionary update sequence element #0 to a sequence 
Enter fullscreen mode Exit fullscreen mode

A dictionary(dict) comprehension can create a dictionary as shown below:

<1D dictionary>:

sample = [0, 1, 2, 3, 4, 5, 6, 7] v = {x:x**2 for x in sample} print(v) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49} 
Enter fullscreen mode Exit fullscreen mode

<2D dictionary>:

sample = ((0, 1, 2, 3), (4, 5, 6, 7)) v = {x: {y:y**2 for y in x} for x in sample} print(v) # {(0, 1, 2, 3): {0: 0, 1: 1, 2: 4, 3: 9}, # (4, 5, 6, 7): {4: 16, 5: 25, 6: 36, 7: 49}} 
Enter fullscreen mode Exit fullscreen mode

<3D dictionary>:

sample = (((0, 1), (2, 3)), ((4, 5), (6, 7))) v = {x: {y: {z:z**2 for z in y} for y in x} for x in sample} print(v) # {((0, 1), (2, 3)): {(0, 1): {0: 0, 1: 1}, (2, 3): {2: 4, 3: 9}}, # ((4, 5), (6, 7)): {(4, 5): {4: 16, 5: 25}, (6, 7): {6: 36, 7: 49}}} 
Enter fullscreen mode Exit fullscreen mode

Be careful, a huge dictionary gets MemoryError as shown below:

v = {x:x for x in range(100000000)} # MemoryError 
Enter fullscreen mode Exit fullscreen mode

A dictionary can be read or changed by keying as shown below:

*Memo:

  • Keying can be done with one or more [key].
  • A del statement can remove one or more pairs of a key and value from a dictionary by keying and can remove one or more variables themselves.

1D dictionary:

v = {'name':'John', 'age':36} v = dict(name='John', age=36) v = dict([('name', 'John'), ('age', 36)]) print(v['name'], v['age']) # John 36  v['name'] = 'Emily' v['gender'] = 'Female' print(v) # {'name': 'Emily', 'age': 36, 'gender': 'Female'}  del v['name'], v['gender'] print(v) # {'age': 36}  del v print(v) # NameError: name 'v' is not defined 
Enter fullscreen mode Exit fullscreen mode

2D dictionary:

v = {'person1':{'name':'John', 'age':36}, 'person2':{'name':'Anna', 'age':24}} v = dict(person1=dict(name='John', age=36), person2=dict(name='Anna', age=24)) v = dict([('person1', dict([('name', 'John'), ('age', 36)])), ('person2', dict([('name', 'Anna'), ('age', 24)]))]) print(v['person1'], v['person2']) # {'name': 'John', 'age': 36} {'name': 'Anna', 'age': 24}  print(v['person1']['name'], v['person1']['age'], v['person2']['name'], v['person2']['age']) # John 36 Anna 24  v['person1']['name'] = 'Emily' v['person2']['gender'] = 'Female' v['person3'] = {'name':'Peter', 'age':18, 'gender':'Male'} print(v) # {'person1': {'name': 'Emily', 'age': 36}, # 'person2': {'name': 'Anna', 'age': 24, 'gender': 'Female'}, # 'person3': {'name': 'Peter', 'age': 18, 'gender': 'Male'}}  del v['person1'] del v['person3']['name'], v['person3']['gender'] print(v) # {'person2': {'name': 'Anna', 'age': 24, 'gender': 'Female'}, # 'person3': {'age': 18}} 
Enter fullscreen mode Exit fullscreen mode

3D dictionary:

v = {'person1':{'name':{'fname':'John', 'lname':'Smith'}}, 'person2':{'name':{'fname':'Anna', 'lname':'Brown'}}} v = dict(person1=dict(name=dict(fname='John', lname='Smith')), person2=dict(name=dict(fname='Anna', lname='Brown'))) v = dict([('person1', dict([('name', dict([('fname', 'John'), ('lname', 'Smith')]))])), ('person2', dict([('name', dict([('fname', 'Anna'), ('lname', 'Brown')]))]))]) print(v['person1'], v['person2']) # {'name': {'fname': 'John', 'lname': 'Smith'}} # {'name': {'fname': 'Anna', 'lname': 'Brown'}}  print(v['person1']['name'], v['person2']['name']) # {'fname': 'John', 'lname': 'Smith'} # {'fname': 'Anna', 'lname': 'Brown'}  v['person1']['name']['fname'] = 'Emily' v['person1']['name']['mname'] = 'Lee' v['person2']['gender'] = 'Female' v['person3'] = {'name':{'fname':'Peter', 'lname':'Davis'}, 'gender':'Male'} print(v) # {'person1': {'name': {'fname': 'Emily', 'lname': 'Smith', # 'mname': 'Lee'}}, # 'person2': {'name': {'fname': 'Anna', 'lname': 'Brown'}, # 'gender': 'Female'}, # 'person3': {'name': {'fname': 'Peter', 'lname': 'Davis'}, # 'gender': 'Male'}}  del v['person1'] del v['person2']['name'] del v['person3']['name']['lname'], v['person3']['gender'] print(v) # {'person2': {'gender': 'Female'}, # 'person3': {'name': {'fname': 'Peter'}}} 
Enter fullscreen mode Exit fullscreen mode

A dictionary can be used like a list by indexing but not by slicing properly as shown below:

v = {0:'apple', 1:'orange', 2:'kiwi'} print(v[0], v[1], v[2]) # Apple Orange Kiwi  v[0] = 'APPLE' v[1] = 'ORANGE' v[2] = 'KIWI' print(v) # {0: 'APPLE', 1: 'ORANGE', 2: 'KIWI'}  v[0:2] = ['banana', 'peach'] print(v) # {0: 'APPLE', 1: 'ORANGE', 2: 'KIWI', slice(0, 2, None): ['banana', 'peach']} 
Enter fullscreen mode Exit fullscreen mode

A dictionary can be continuously used through multiple variables as shown below:

v1 = v2 = v3 = {'name':'John', 'age':36, 'gender':'Male'} # Equivalent  # v1 = {'name':'John', 'age':36, 'gender':'Male'}  # v2 = v1  # v3 = v2 v1['name'] = 'Anna' v2['age'] = 24 v3['gender'] = 'Female' print(v1) # {'name': 'Anna', 'age': 24, 'gender': 'Female'} print(v2) # {'name': 'Anna', 'age': 24, 'gender': 'Female'} print(v3) # {'name': 'Anna', 'age': 24, 'gender': 'Female'} 
Enter fullscreen mode Exit fullscreen mode

The variables v1 and v2 refer to the same dictionary unless copied as shown below:

*Memo:

  • is keyword or is and not keyword can check if v1 and v2 refer or don't refer to the same dictionary respectively.
  • dict.copy(), copy.copy() and dict() do shallow copy:
    • dict.copy() has no arguments.
  • deepcopy() does deep copy.
  • copy.deepcopy() should be used because it's safe, doing copy deeply while dict.copy(), copy.copy() and dict() aren't safe, doing copy shallowly.
import copy v1 = {'name':'John', 'age':36} v2 = v1 # v2 refers to the same dictionary as v1.  v2['name'] = 'Emily' # Changes the same dictionary as v1.  # ↓↓↓↓↓↓↓ print(v1) # {'name': 'Emily', 'age': 36} print(v2) # {'name': 'Emily', 'age': 36}  # ↑↑↑↑↑↑↑ print(v1 is v2, v1 is not v2) # True False  v2 = v1.copy() # v2 refers to the different dictionary from v1. v2 = copy.copy(v1) v2 = copy.deepcopy(v1) v2 = dict(v1) v2['name'] = 'Anna' # Changes the different dictionary from v1.  # ↓↓↓↓↓↓↓ print(v1) # {'name': 'Emily', 'age': 36} print(v2) # {'name': 'Anna', 'age': 36}  # ↑↑↑↑↑↑ print(v1 is v2, v1 is not v2) # False True 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)