DEV Community

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

Posted on

Dictionary in Python (2)

Buy Me a Coffee

*Memos:

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

dict() can create a dictionary with or without a dictonary as shown below:

*Memos:

  • The 1st argument is iterable(Optional-Type:iterable). *Don't use iterable=.
  • The 2nd or the later arguments are **kwarg(Optional). *Don't use any keywords like **kwarg=, kwarg=, **kwargs=, kwargs=, etc.
print(dict()) # []

print(dict({'name':'John', 'age':36})) # Dictionary
print(dict([('name', 'John'), ('age', 36)]))
print(dict({'name':'John'}, age=36))
print(dict([('name', 'John')], age=36))
print(dict(name='John', age=36))
# {'name': 'John', 'age': 36}
Enter fullscreen mode Exit fullscreen mode

dict() cannot create a dictionary with a list, tuple, set, iterator, string or range() as shown below:

v = ['a', 'b', 'c', 'd', 'e']

print(dict(v))
# ValueError: dictionary update sequence element #0 has length 1; 2 is required
Enter fullscreen mode Exit fullscreen mode
v = ('a', 'b', 'c', 'd', 'e')

print(dict(v))
# ValueError: dictionary update sequence element #0 has length 1; 2 is required
Enter fullscreen mode Exit fullscreen mode
v = {'a', 'b', 'c', 'd', 'e'}

print(dict(v))
# ValueError: dictionary update sequence element #0 has length 1; 2 is required
Enter fullscreen mode Exit fullscreen mode
v = iter(['a', 'b', 'c', 'd', 'e']) # Iterator

print(dict(v))
# ValueError: dictionary update sequence element #0 has length 1; 2 is required
Enter fullscreen mode Exit fullscreen mode
v = 'Hello' # String

print(dict(v))
# ValueError: dictionary update sequence element #0 has length 1; 2 is required
Enter fullscreen mode Exit fullscreen mode
v = range(5)

print(dict(v))
# TypeError: cannot convert dictionary update sequence element #0 to a sequence
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

You can access and change a dictionary by keying as shown below. *Keying can be done with one or more [key]:

v = {'name':'John', 'age':36} # 1D dictionary
v = dict(name='John', age=36)
v = dict([('name', 'John'), ('age', 36)])

print(v['name'], v['age'])
# John 36

print(v[0]) # KeyError: 0
print(v[0:2]) # KeyError: slice(0, 2, None)

v['name'] = 'David'
v['gender'] = 'Male'

print(v)
# {'name': 'David', 'age': 36, 'gender': 'Male'}
Enter fullscreen mode Exit fullscreen mode
v = {'person1':{'name':'John', 'age':36}, # 2D dictionary
     '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'] = 'David'
v['person2']['gender'] = 'Female'
v['person3'] = {'name':'Tom', 'age':18, 'gender':'Male'}

print(v)
# {'person1': {'name': 'David', 'age': 36},
#  'person2': {'name': 'Anna', 'age': 24, 'gender': 'Female'},
#  'person3': {'name': 'Tom', 'age': 18, 'gender': 'Male'}}
Enter fullscreen mode Exit fullscreen mode

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

*Memos:

  • is keyword can check if v1 and v2 refer to the same dictionary.
  • copy() can do shallow copy. *There are no arguments.
  • deepcopy() can do deep copy. *There are no arguments.
  • deepcopy() should be used because it's safe, doing copy deeply while copy() isn't safe, doing copy shallowly.
from copy import deepcopy

v1 = {'name':'John', 'age':36}

v2 = v1 # v2 refers to the same dictionary as v1.

v2['name'] = 'David' # Changes the same dictionary as v1.
                   # ↓↓↓↓↓↓↓
print(v1) # {'name': 'David', 'age': 36}
print(v2) # {'name': 'David', 'age': 36}
                   # ↑↑↑↑↑↑↑
print(v1 is v2) # True

v2 = v1.copy()    # v2 refers to the different dictionary from v1.
v2 = deepcopy(v1)

v2['name'] = 'Anna' # Changes the different dictionary from v1.
                   # ↓↓↓↓↓↓↓
print(v1) # {'name': 'David', 'age': 36}
print(v2) # {'name': 'Anna', 'age': 36}
                   # ↑↑↑↑↑↑
print(v1 is v2) # False
Enter fullscreen mode Exit fullscreen mode

Top comments (0)