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 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 an iterator (1).
  • My post explains a string.
  • My post explains a bytes.
  • My post explains a bytearray.

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 pairs of a key and value in a dictionary is kept so it guarantees that the order is always the same unless someone or something changes it.
    • From Python 3.7, dictionaries are ordered so until Python 3.6, dictionaries are unordered.
  • shouldn't be huge not to get MemoryError.
  • doesn't allow duplicated keys (even with different types):
    • The values of the last duplicated keys are used.
  • is mutable 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 element is or isn't in it with in keyword or not and in keyword respectively.
  • can be checked if it is or isn't referred to by two variables with is keyword or not and is keyword respectively.
  • 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 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 copied to refer to a different dictionary.

A dictionary is for non-huge data otherwise it gets MemoryError.


{} 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}}
# No error

v = {0:'A', 0.0:'B', 0.0+0.0j:'C', False:'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 v in {0:1, 2:3, 4:5}: 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})
print([*{0:1, 2:3, 4:5}, *{6:7, 8:9}])
print({**{'A':'B', 'C':'D', **{'E':'F'}}, **{'G':'H', 'I':'J'}})
v = {x:x**2 for x in range(6)}
# No error

print(**{'A':'B', 'C':'D', 'E':'F', 'G':'H', 'I':'J'})
v = {x:x for x in range(100000000)}
# Error

v = {bytearray(b'Hello'):bytearray(b'World')}
# TypeError: unhashable type: 'bytearray'

v = {[2, 3]:[4, 5]} 
# TypeError: unhashable type: 'list'

v = {{2, 3}:{4, 5}}
# TypeError: unhashable type: 'set'

v = {{'A':'a'}:{'B':'b'}}
# TypeError: unhashable type: 'dict'

v = {'name':'John', 'age':36} * 3
# TypeError: unsupported operand type(s) for *: 'dict' and 'int'
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 can be iterated with a for statement as shown below:

for v in {0:1, 2:3, 4:5}:          # dict
# for v in {0:1, 2:3, 4:5}.keys(): # dict.keys()
    print(v)
# 0
# 2
# 4

for v in {0:1, 2:3, 4:5}.values(): # dict.values()
    print(v)
# 1
# 3
# 5

for v in {0:1, 2:3, 4:5}.items():  # dict.items()
    print(v)
# (0, 1)
# (2, 3)
# (4, 5)
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
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
print(*{0:1, 2:3, 4:5}, *{6:7, 8:9})                   # dict
print(*{0:1, 2:3, 4:5}.keys(), *{6:7, 8:9}.keys())     # dict.keys()
# 0 2 4 6 8

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

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

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

print([*{0:1, 2:3, 4:5}.items(), *{6:7, 8:9}.items()])   # dict.items()
# [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
Enter fullscreen mode Exit fullscreen mode
print({**{'A':'B', 'C':'D', **{'E':'F'}}, **{'G':'H', 'I':'J'}})
# {'A': 'B', 'C': 'D', 'E': 'F', 'G': 'H', 'I': 'J'}
Enter fullscreen mode Exit fullscreen mode
print(**{'A':'B', 'C':'D', 'E':'F', 'G':'H', 'I':'J'})
# TypeError: 'A' is an invalid keyword argument for print()
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 or aren't in it with in keyword or not and in keyword respectively 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
v = {'A':'B', 'C':{'D':'E'}}
v = {'A':'B', 'C':{'D':'E'}}.keys()

print('A' not in v)
# False

print('B' not in v)
# True

print({'D':'E'} not in v)
print(('C', {'D': 'E'}) not 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
v = {'A':'B', 'C':{'D':'E'}}.values()

print('A' not in v)
# True

print('B' not in v)
# False

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

print(('C', {'D': 'E'}) not in v)
# True
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
v = {'A':'B', 'C':{'D':'E'}}.items()

print('A' not in v)
# True

print('B' not in v)
# True

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

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

Top comments (0)