DEV Community

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

Posted on • Edited on

Dictionary in Python (7)

Buy Me a Coffee

*Memo:

  • My post explains a dictionary (1).
  • My post explains a dictionary (2).
  • My post explains a dictionary (3).
  • My post explains a dictionary (4).
  • My post explains a dictionary (5).
  • My post explains a dictionary (6).
  • My post explains a dictionary (8).

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

*Memo:

  • The 1st argument is mapping or iterable(Optional-Type:Mapping/Iterable):
    • mapping is a dictionary.
    • iterable is e.g. [(key, value), ...].
    • Don't use mapping= and 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']),           # set(frozenset)
            frozenset(['age', 36])}))
print(dict(frozenset([frozenset(['name', 'John']), # frozenset(frozenset)
           frozenset(['age', 36])])))
print(dict(iter([iter(['name', 'John']),           # iter(iter)
                 iter(['age', 36])])))
# {'name': 'John', 'age': 36}
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 a non-empty 1D 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 big dictionary gets MemoryError as shown below:

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

Top comments (0)