A dictionary stores data as key:value pairs — you look up a value by its key. Here are 5 examples: basic lookup, looping over items (.items()), a list value, turning keys into a list (list(dict.keys())), and using _ as the key name.
Example 1: create a dict and read by key #
dict1={"key1":"john", "key2":"paul"}
print (dict1["key1"])output:
john
Example 2: loop over key and value (.items()) #
my_dict = {'apple': 3, 'banana': 5, 'orange': 2}
for key, value in my_dict.items():
print(f'{key} : {value}')output:
apple : 3 banana : 5 orange : 2
Example 3: value is a list #
dictStu = {'StuName': ['Ada, Billy, Cindy'], 'ChiScore': [10,20,30]}
for key in dictStu:
print(f'{key}: {dictStu[key]}')output:
StuName: ['Ada, Billy, Cindy'] ChiScore: [10, 20, 30]
Example 4: turn keys into a list (list(dict.keys())) #
dictStu = {'StuName': 'Ada',
'ChiScore': 'A'}
keys = list(dictStu.keys())
print(keys)
count=0
while (count<len(keys)):
print (f'{keys[count]}:{dictStu[keys[count]]}')
count=count+1output:
['StuName', 'ChiScore'] StuName:Ada ChiScore:A
Example 5: use _ as the key name #
dict1 = {'aaa':111, 'bbb':222, 'ccc':333}
for _, value in dict1.items():
print (f'key={_}, value={value}')output:
key=aaa, value=111 key=bbb, value=222 key=ccc, value=333
