*Memo:
- My post explains a dictionary (1).
- My post explains a dictionary (2).
- My post explains a dictionary (4).
- 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
oriterable
(Optional-Type:Mapping or Iterable):- Don't use
mapping=
oriterable=
.
- Don't use
- The 2nd arguments are
**kwargs
(Optional-Default:{}
-Type:Any):- Don't use any keywords like
**kwargs=
,kwargs=
, etc.
- Don't use any keywords like
# 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'}
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
# {}
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
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}
<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}}
<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}}}
Be careful, a huge dictionary gets MemoryError
as shown below:
v = {x:x for x in range(1000000000)}
# MemoryError
A dictionary can be read by keying or changed by keying and a del statement 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
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}}
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'}}}
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']}
Top comments (0)