DEV Community

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

Posted on • Edited on

Dictionary in Python (1)

Buy Me a Coffee

*Memo:

  • My post explains a dictionary (2) and the dictionary with keying and copy.
  • My post explains dictionary functions (1).
  • My post explains dictionary functions (2).
  • My post explains a set and dictionary(dict) comprehension.
  • My post explains the shallow and deep copy of a dictionary.
  • My post explains a list and the list with indexing.
  • My post explains a tuple.
  • My post explains a set and the set with copy.
  • My post explains a frozenset (1).
  • My post explains an iterator (1).
  • My post explains a string.
  • My post explains a bytes.
  • My post explains a bytearray.
  • My post explains a range (1).

A dictionary(dict):

  • is the ordered collection of zero or more pairs of a key and value(key:value) whose type is dict:
    • Ordered means that the order of each pair of a key and value in a dictionary is kept so it guarantees that the order is always the same unless changed.
    • From Python 3.7, dictionaries are ordered so until Python 3.6, dictionaries are unordered.
  • cannot be huge because it gets MemoryError.
  • doesn't allow duplicated keys (even with different types):
    • The values of the last duplicated keys are used.
  • is mutable(unhashable) so it can be changed.
  • can have the hashable types of keys and any types of values:
    • The unhashable types of keys are unavailable.
    • A hashable type is the type whose value cannot be changed like str, bytes, int, float, complex, bool, tuple, frozenset, range or iterator.
    • A unhashable type is the type whose value can be changed like bytearray, list, set or dict.
  • can be iterated with a for statement.
  • can be unpacked with an assignment and for statement, function, * and **.
  • is False if it's empty.
  • can be checked if a specific key and/or value are in the dictionary with in keyword.
  • can be checked if the dictionary is referred to by two variables with is keyword.
  • cannot be enlarged with * and a number.
  • can be created by {}, dict() in many ways or a dictionary(dict) comprehension:
    • dict() can create a dictionary with dict, keyword arguments(kwargs) and a 2D iterable(list, tuple, set, frozenset and iterator).
    • dict() can also create a dictionary with an empty 1D iterable.
    • dict() cannot create a dictionary with only one unempty iterable except dict.
    • For dict(), the words type conversion are also suitable in addition to the word creation.
  • can be used with len() to get the length.
  • can be read or changed by keying.
  • can be used like a list to be read or changed by indexing but not by slicing properly.
  • can be continuously used through multiple variables.
  • can be shallow-copied and deep-copied.

{} can create a dictionary as shown below:

v = {}                                                     # Empty 1D dict
v = {'name':'John', 'age':36}                              # 1D dict
v = {'name':'John', 'age':36, 'name':'Anna', 'age':24}     # 1D dict
v = {0:'apple', 1:'orange', 2:'kiwi'}                      # 1D dict
v = {'person1':{'name':'John', 'age':36},                  # 2D dict
     'person2':{'name':'Anna', 'age':24}}
v = {'person1':{'name':{'fname':'John', 'lname':'Smith'}}, # 3D dict
     'person2':{'name':{'fname':'Anna', 'lname':'Brown'}}}
# No error

v = {0:'A', 0.0:'B', 0.0+0.0j:'C', False:'D'}
v = {1:'A', 1.0:'B', 1.0+0.0j:'C', True:'D'}
v = {'A':'a', b'A':b'a', 'BA':bytearray(b'a'),
     2:3, 2.3:4.5, 2.3+4.5j:6.7+8.9j, True:False,
     'L':[4, 5], (2, 3):(4, 5), 'S':{4, 5},
     frozenset({2, 3}):frozenset({4, 5}), 'D':{'A':'a'},
     range(2, 3):range(4, 5),
     iter([2, 3]):iter([4, 5])}
for x in {0:1, 2:3, 4:5}: pass
for x in {0:{1:2}, 3:{4:5}, 6:{7:8}}: pass
v1, v2, v3 = {0:1, 2:3, 4:5}
v1, *v2, v3 = {0:1, 2:3, 4:5, 6:7, 8:9, 10:11}
for v1, v2, v3 in [{0:1, 2:3, 4:5}, {6:7, 8:9, 10:11}]: pass
for v1, *v2, v3 in [{0:1, 2:3, 4:5, 6:7, 8:9, 10:11},
                    {12:13, 14:15, 16:17, 18:19, 20:21, 22:23}]: pass
print(*{0:1, 2:3, 4:5, 6:7}, *{8:9, 10:11})
print([*{0:1, 2:3, 4:5, 6:7}, *{8:9, 10:11}])
print({**{0:1, 2:3, 4:5, 6:7, 8:9, 10:11}})
print({**{0:1, 2:3}, 4:5, **{6:7, 8:9, **{10:11}}})
v = {x:x**2 for x in [0, 1, 2, 3, 4, 5, 6, 7]}
v = {x: {y:y**2 for y in x} for x in ((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 (((0, 1), (2, 3)),
                                                      ((4, 5), (6, 7)))}
# No error

v = {[2, 3]:'val'}
v = {{2, 3}:'val'}
v = {{'A':'a'}:'val'}
v = {bytearray(b'Hello'):'val'}
v = {'name':'John', 'age':36} * 3
v = {x:x for x in range(1000000000)}
# Error
Enter fullscreen mode Exit fullscreen mode

A dictionary is the ordered collection of zero or more pairs of a key and value(key:value) whose type is dict as shown below:

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

print(v)
# {'name': 'John', 'age': 36}

print(type(v))
# <class 'dict'>
Enter fullscreen mode Exit fullscreen mode
v = {} # Empty dict

print(v)
# {}
Enter fullscreen mode Exit fullscreen mode

A dictionary doesn't allow duplicated keys (even with different types) as shown below:

*Memo:

  • The value of the last duplicated key is used:
v = {'name':'John', 'age':36, 'name':'Anna', 'age':24}

print(v)
# {'name': 'Anna', 'age': 24}
Enter fullscreen mode Exit fullscreen mode
v = {0:'A', 0.0:'B', 0.0+0.0j:'C', False:'D'}

print(v)
# {0: 'D'}
Enter fullscreen mode Exit fullscreen mode
v = {1:'A', 1.0:'B', 1.0+0.0j:'C', True:'D'}

print(v)
# {1: 'D'}
Enter fullscreen mode Exit fullscreen mode

A dictionary can have the hashable types of keys and any types of values as shown below:

v = {'A':'a', b'A':b'a', 'BA':bytearray(b'a'),
     2:3, 2.3:4.5, 2.3+4.5j:6.7+8.9j, True:False,
     'L':[4, 5], (2, 3):(4, 5), 'S':{4, 5},
     frozenset({2, 3}):frozenset({4, 5}), 'D':{'A':'a'},
     range(2, 3):range(4, 5),
     iter([2, 3]):iter([4, 5])}
print(v)
# {'A': 'a', b'A': b'a', 'BA': bytearray(b'a'),
#  2: 3, 2.3: 4.5, (2.3+4.5j): (6.7+8.9j), True: False,
#  'L': [4, 5], (2, 3): (4, 5), 'S': {4, 5},
#  frozenset({2, 3}): frozenset({4, 5}), 'D': {'A': 'a'},
#  range(2, 3): range(4, 5),
#  <list_iterator object at 0x0000026B40AECFA0>:
#  <list_iterator object at 0x0000026B4209F310>}

print(v['A'], v[b'A'], v['BA'], v[2], v[2.3], v[2.3+4.5j],
      v[True], v['L'], v[(2, 3)], v['S'], v[frozenset({2, 3})], v['D'],
      v[range(2, 3)], v[list(v.keys())[-1]])
# a b'a' bytearray(b'a') 3 4.5 (6.7+8.9j)
# False [4, 5] (4, 5) {4, 5} frozenset({4, 5}) {'A': 'a'} range(4, 5)
# <list_iterator object at 0x0000026B4209E6E0>
Enter fullscreen mode Exit fullscreen mode
v = {'':'A', b'': b'A', ():(2, 3),
     frozenset():frozenset({2, 3}), range(0):range(2, 3),
     iter([2, 3]):iter([2, 3])}
print(v)
# {'': 'A', b'': b'A', (): (2, 3),
#  frozenset(): frozenset({2, 3}), range(0, 0): range(2, 3),
#  <list_iterator object at 0x0000026B3FD51330>:
#  <list_iterator object at 0x0000026B403883A0>}

print(v[''], v[b''], v[()],
      v[frozenset()], v[range(0)],
      v[list(v.keys())[-1]])
# A b'A' (2, 3)
# frozenset({2, 3}) range(2, 3)
# <list_iterator object at 0x0000026B3F1F3280>
Enter fullscreen mode Exit fullscreen mode

A dictionary cannot have the unhashable types of keys as shown below:

v = {[2, 3]:'val'}              # dict(list:str)
# TypeError: unhashable type: 'list'

v = {{2, 3}:'val'}              # dict(set:str)
# TypeError: unhashable type: 'set'

v = {{'A':'a'}:'val'}           # dict(dict:str)
# TypeError: unhashable type: 'dict'

v = {bytearray(b'Hello'):'val'} # dict(bytearray:str)
# TypeError: unhashable type: 'bytearray'
Enter fullscreen mode Exit fullscreen mode

A dictionary can be iterated with a for statement as shown below:

<1D dictionary>:

keys():

for x in {0:1, 2:3, 4:5}:          # dict
# for x in {0:1, 2:3, 4:5}.keys(): # dict.keys()
    print(x)
# 0
# 2
# 4
Enter fullscreen mode Exit fullscreen mode

values():

for x in {0:1, 2:3, 4:5}.values(): # dict.values()
    print(x)
# 1
# 3
# 5
Enter fullscreen mode Exit fullscreen mode

items():

for x in {0:1, 2:3, 4:5}.items():  # dict.items()
    print(x)
# (0, 1)
# (2, 3)
# (4, 5)
Enter fullscreen mode Exit fullscreen mode

<2D dictionary>:

keys():

for x in {0:{1:2}, 3:{4:5}, 6:{7:8}}:          # dict
# for x in {0:{1:2}, 3:{4:5}, 6:{7:8}}.keys(): # dict.keys()
    print(x)
# 0
# 3
# 6
Enter fullscreen mode Exit fullscreen mode

values():

for x in {0:{1:2}, 3:{4:5}, 6:{7:8}}.values(): # dict.values()
    for y in x:                                # dict
    # for y in x.keys():                       # dict.keys()
        print(y)
# 1
# 4
# 7

for x in {0:{1:2}, 3:{4:5}, 6:{7:8}}.values(): # dict.values()
    for y in x.values():                       # dict.values()
        print(y)
# 2
# 5
# 8

for x in {0:{1:2}, 3:{4:5}, 6:{7:8}}.values(): # dict.values()
    for y in x.items():                        # dict.items()
        print(y)
# (1, 2)
# (4, 5)
# (7, 8)
Enter fullscreen mode Exit fullscreen mode

items():

for x in {0:{1:2}, 3:{4:5}, 6:{7:8}}.items(): # dict.items()
    for y in x:                               # tuple
        if isinstance(y, dict):
            for z in y:                       # dict
            # for z in y.keys():              # dict.keys()
                print(z)
        else:
            print(y)
# 0
# 1
# 3
# 4
# 6
# 7

for x in {0:{1:2}, 3:{4:5}, 6:{7:8}}.items(): # dict.items()
    for y in x:                               # tuple
        if isinstance(y, dict):
            for z in y.values():              # dict.values()
                print(z)
        else:
            print(y)
# 0
# 2
# 3
# 5
# 6
# 8

for x in {0:{1:2}, 3:{4:5}, 6:{7:8}}.items(): # dict.items()
    for y in x:                               # tuple
        if isinstance(y, dict):
            for z in y.items():               # dict.items()
                print(z)
        else:
            print(y)
# 0
# (1, 2)
# 3
# (4, 5)
# 6
# (7, 8)
Enter fullscreen mode Exit fullscreen mode

A dictionary can be unpacked with an assignment and for statement, function, * and ** as shown below:

v1, v2, v3 = {0:1, 2:3, 4:5}          # dict
v1, v2, v3 = {0:1, 2:3, 4:5}.keys()   # dict.keys()

print(v1, v2, v3)
# 0 2 4

v1, v2, v3 = {0:1, 2:3, 4:5}.values() # dict.values()

print(v1, v2, v3)
# 1 3 5

v1, v2, v3 = {0:1, 2:3, 4:5}.items()  # dict.items()

print(v1, v2, v3)
# (0, 1) (2, 3) (4, 5)
Enter fullscreen mode Exit fullscreen mode
v1, *v2, v3 = {0:1, 2:3, 4:5, 6:7, 8:9, 10:11}          # dict
v1, *v2, v3 = {0:1, 2:3, 4:5, 6:7, 8:9, 10:11}.keys()   # dict.keys()

print(v1, v2, v3)
# 0 [2, 4, 6, 8] 10

v1, *v2, v3 = {0:1, 2:3, 4:5, 6:7, 8:9, 10:11}.values() # dict.values()

print(v1, v2, v3)
# 1 [3, 5, 7, 9] 11

v1, *v2, v3 = {0:1, 2:3, 4:5, 6:7, 8:9, 10:11}.items()  # dict.items()

print(v1, v2, v3)
# (0, 1) [(2, 3), (4, 5), (6, 7), (8, 9)] (10, 11)
Enter fullscreen mode Exit fullscreen mode
for v1, v2, v3 in [{0:1, 2:3, 4:5},             # list(dict)
                   {6:7, 8:9, 10:11}]:
# for v1, v2, v3 in [{0:1, 2:3, 4:5}.keys(),    # list(dict.keys())
#                    {6:7, 8:9, 10:11}.keys()]:
    print(v1, v2, v3)
# 0 2 4
# 6 8 10

for v1, v2, v3 in [{0:1, 2:3, 4:5}.values(),    # list(dict.values())
                   {6:7, 8:9, 10:11}.values()]:
    print(v1, v2, v3)
# 1 3 5
# 7 9 11

for v1, v2, v3 in [{0:1, 2:3, 4:5}.items(),     # list(dict.items())
                   {6:7, 8:9, 10:11}.items()]:
    print(v1, v2, v3)
# (0, 1) (2, 3) (4, 5)
# (6, 7) (8, 9) (10, 11)
Enter fullscreen mode Exit fullscreen mode
# list(dict)
for v1, *v2, v3 in [{0:1, 2:3, 4:5, 6:7, 8:9, 10:11},
                    {12:13, 14:15, 16:17, 18:19, 20:21, 22:23}]:
# list(dict.keys())
# for v1, *v2, v3 in [{0:1, 2:3, 4:5, 6:7, 8:9, 10:11}.keys(), 
#                     {12:13, 14:15, 16:17, 18:19, 20:21, 22:23}.keys()]:
    print(v1, v2, v3)
    print(v1, *v2, v3)
# 0 [2, 4, 6, 8] 10
# 0 2 4 6 8 10
# 12 [14, 16, 18, 20] 22
# 12 14 16 18 20 22

# list(dict.values())
for v1, *v2, v3 in [{0:1, 2:3, 4:5, 6:7, 8:9, 10:11}.values(), 
                    {12:13, 14:15, 16:17, 18:19, 20:21, 22:23}.values()]:
    print(v1, v2, v3)
    print(v1, *v2, v3)
# 1 [3, 5, 7, 9] 11
# 1 3 5 7 9 11
# 13 [15, 17, 19, 21] 23
# 13 15 17 19 21 23

# list(dict.items())
for v1, *v2, v3 in [{0:1, 2:3, 4:5, 6:7, 8:9, 10:11}.items(),  
                    {12:13, 14:15, 16:17, 18:19, 20:21, 22:23}.items()]:
    print(v1, v2, v3)
    print(v1, *v2, v3)
# (0, 1) [(2, 3), (4, 5), (6, 7), (8, 9)] (10, 11)
# (0, 1) (2, 3) (4, 5) (6, 7) (8, 9) (10, 11)
# (12, 13) [(14, 15), (16, 17), (18, 19), (20, 21)] (22, 23)
# (12, 13) (14, 15) (16, 17) (18, 19) (20, 21) (22, 23)
Enter fullscreen mode Exit fullscreen mode
print(*{0:1, 2:3, 4:5, 6:7}, *{8:9, 10:11}) # dict
print(*{0:1, 2:3, 4:5, 6:7}.keys(),         # dict.keys()
      *{8:9, 10:11}.keys())     
# 0 2 4 6 8 10

print(*{0:1, 2:3, 4:5, 6:7}.values(),       # dict.values()
      *{8:9, 10:11}.values())
# 1 3 5 7 9 11

print(*{0:1, 2:3, 4:5, 6:7}.items(),        # dict.items()
      *{8:9, 10:11}.items())
# (0, 1) (2, 3) (4, 5) (6, 7) (8, 9) (10, 11)
Enter fullscreen mode Exit fullscreen mode
print([*{0:1, 2:3, 4:5, 6:7}, *{8:9, 10:11}]) # dict
print([*{0:1, 2:3, 4:5, 6:7}.keys(),          # dict.keys()
       *{8:9, 10:11}.keys()])
# [0, 2, 4, 6, 8, 10]

print([*{0:1, 2:3, 4:5, 6:7}.values(),        # dict.values()
       *{8:9, 10:11}.values()])
# [1, 3, 5, 7, 9, 11]

print([*{0:1, 2:3, 4:5, 6:7}.items(),         # dict.items()
       *{8:9, 10:11}.items()])
# [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)]
Enter fullscreen mode Exit fullscreen mode
print({**{0:1, 2:3, 4:5, 6:7, 8:9, 10:11}})
print({**{0:1, 2:3}, 4:5, **{6:7, 8:9, **{10:11}}})
# {0: 1, 2: 3, 4: 5, 6: 7, 8: 9, 10: 11}
Enter fullscreen mode Exit fullscreen mode
def func(A='b', C='d'):
    print(A, C)

func()
# b d

func(**{'A':'B', 'C':'D'})
func(**{'A':'B'}, **{'C':'D'})
func(A='B', **{'C':'D'})
func(**{'A':'B'}, C='D')
func(A='B', C='D')
# B D
Enter fullscreen mode Exit fullscreen mode
def func(A='b', **kwargs):
    print(A, kwargs)
    print(A, {0:1, **kwargs, 2:3})

func()
# b {}
# b {0: 1, 2: 3}

func(**{'A':'B', 'C':'D'})
func(**{'A':'B'}, **{'C':'D'})
func(A='B', **{'C':'D'})
func(**{'A':'B'}, C='D')
func(A='B', C='D')
# B {'C': 'D'}
# B {0: 1, 'C': 'D', 2: 3}
Enter fullscreen mode Exit fullscreen mode

An empty dictionary is False as shown below:

print(bool({}))      # Empty dict
# False

print(bool({0:0}))   # dict
print(bool({():()})) # dict(Empty tuple:Empty tuple)
# True
Enter fullscreen mode Exit fullscreen mode

A dictionary can be checked if a specific key and/or value are in the dictionary with in keyword as shown below:

<keys()>:

v = {'A':'B', 'C':{'D':'E'}}
v = {'A':'B', 'C':{'D':'E'}}.keys()

print('A' in v)
# True

print('B' in v)
# False

print({'D':'E'} in v)
print(('C', {'D': 'E'}) in v)
# TypeError: unhashable type: 'dict'
Enter fullscreen mode Exit fullscreen mode

<values()>:

v = {'A':'B', 'C':{'D':'E'}}.values()

print('A' in v)
# False

print('B' in v)
# True

print({'D':'E'} in v)
# True

print(('C', {'D': 'E'}) in v)
# False
Enter fullscreen mode Exit fullscreen mode

<items()>:

v = {'A':'B', 'C':{'D':'E'}}.items()

print('A' in v)
# False

print('B' in v)
# False

print({'D': 'E'} in v)
# False

print(('C', {'D': 'E'}) in v)
# True
Enter fullscreen mode Exit fullscreen mode

A dictionary cannot be enlarged with * and a number as shown below:

v = {'name':'John', 'age':36} * 3
# TypeError: unsupported operand type(s) for *: 'dict' and 'int'
Enter fullscreen mode Exit fullscreen mode

Top comments (0)