Python/dictionaries: Difference between revisions
No edit summary |
No edit summary |
||
Line 43: | Line 43: | ||
</source> | </source> | ||
[[Category:Python]] |
Revision as of 10:37, 6 October 2020
How to read/write dictionaries?
d = dict()
# or
d = {}
# Key : Value structure
d = { 'software' : 10 }
# Read a value from the dictionary
print(d['software'])
# 10
# Add a new key to the dictionary
d['language'] = 6
word = 'hello'
if word in d:
print(f'{word} is in the dictionary')
else:
print(f'{word} is not in the dictionary')
Sort a dictionary
keys = []
# key : value
for key, value in d.items():
keys.append(key)
keys.sort()
print(keys)
for key in keys:
print(f'{key} is here so many times:', d[key])