Dictionary, What, Create a dictionary, Example, Merge dictionaries, kwargs, multiple dictionaries, with example, coding, make game, pygame, course
Dictionary
A dictionary is a collection that is unordered, changeable, and indexed. In Python, dictionaries are written with curly brackets{}, and they have keys and values.
Create a dictionary:
In Python, a Dictionary can be created by placing a sequence of elements within the curly brackets, separated by 'comma'. Dictionary holds a pair of values, one being the Key and the other corresponding pair element being its like 'Key: value'.
Example:
alpha = {
'nadim': 5,
'niyaz': 9,
'nila':4
}
codist = {
'tim': 8,
'rahim':4,
'nadim':9
}
Take or read data from the dictionary:
Example:
alpha = {
'nadim': 5,
'niyaz': 9,
'nila':4
}
codist = {
'tim': 8,
'rahim':4,
'nadim':9
}
Data = alpha['nadim']
print(Data)
Merge dictionaries:
In Python, the Dictionary class provides a function update() i.e. 'dictionatyname.update(seconddictionaryname)' It accepts another dictionary or an Iterable object (collection of key-value pairs) as an argument. Then merges the contents of this passed dictionary or Iterable in the current dictionary.
Example:
alpha = {
'nadim': 5,
'niyaz': 9,
'nila':4
}
codist = {
'tim': 8,
'rahim':4,
'nadim':9
}
alpha.update(codist)
print(alpha)
Result:
Using **kwargs we can send variable length key-value pairs to a function. When we apply '**' to a dictionary, then it expands the contents in the dictionary as a collection of key-value pairs
as an example, if we have a dictionary:
alpha = {
'nadim': 5,
'niyaz': 9,
'nila':4
}
codist = {
'tim': 8,
'rahim':4,
'nadim':9
}
best = {**alpha, **codist}
print(best)
Result:
You can merge multiple dictionaries using kwargs.
Example:
alpha = {
'nadim': 5,
'niyaz': 9,
'nila':4
}
codist = {
'tim': 8,
'rahim':4,
'nadim':9
}
best = {
'jerry':7,
'bob': 71,
'rahim':58
}
site = {**alpha, **codist, **best}
print(site)
COMMENTS