Python - Dictionary
Python dictionary stores data in key/value pairs.
my_dict = {
'name': 'Felipe',
'followers': 1337,
'website': 'https://izolipe.com'
}
Access Dictionary Values
To access a dictionary value, use the key inside square brackets ['key']
.
book = {
name = "The Biography of Globglogabgalab",
pages = 667
}
print(book['name']) # The Biography of Globglogabgalab
print(book['pages']) # 667
Add/Edit Dictionary Values
To add/edit a dictionary value, you have two options:
dict['key'] = value
- add/edit values using a key/value.update(iterable)
- update dictionary using a iterable.
player = {}
player['nick'] = 'Xx007SlayerxX'
player['life'] = 52
player.update({ 'max_life': 100, 'items': [ 'sword', 'shield', 'apple' ] })
Remove Dictionary Values
To remove a dictionary value, you have two options:
pop(key)
- remove the item by key.del dict['key']
- remove the item by key usingdel
keyword.
item = {
'id': 32,
'name': 'The Elixir of Chemicals',
'effect': '+ Intelligence'
}
item.pop('effect')
del item['name']
Dictionary Length
To obtain the length of a dictionary use len(x)
.
pikachu = {
"name": "Pikachu",
"type": "Electric",
"height": "0.4 m",
"weight": "6.0 kg",
"abilities": ["Static", "Lightning Rod (hidden ability)"]
}
print(len(pikachu)) # 5