--A memorandum on how to retrieve the elements of the ``` list
and
dictionary
--There are many other things such as adding and deleting elements, but here we will summarize only how to retrieve elements.
――What I found useful while using it is that you can combine `list`
and `dictionary`
.
――In particular, I personally use it most often because I can nest the `dictionary`
inside the `dictionary`
.
--A row of data of the same type --Each element is indexed in order from 0
list.py
ls = ['Apple', 'Peaches', 'Cherry']
print(ls[0])
print(ls[1])
print(ls[2])
result
Apple
Peaches
Cherry
list2.py
ls = ['Apple', 'Peaches', 'Cherry']
for a in ls:
print(a)
result
Apple
Peaches
Cherry
--A collection of data with keys and elements
dic.py
dic = {'fruits':'Apple', 'Vegetables':'onion'}
print(dic['fruits'])
print(dic['Vegetables'])
result
Apple
onion
--You can get `key``` by using
keys
``
dic2.py
dic = {'fruits':'Apple', 'Vegetables':'onion'}
for mykey in dic.keys():
print(mykey)
result
fruits
Vegetables
--You can get `value``` by using
values
``
dic2.py
dic = {'fruits':'Apple', 'Vegetables':'onion'}
for myval in dic.values():
print(myval)
result
Apple
onion
--You can get both `key``` and
`valueby using
items```
dic3.py
dic = {'fruits':'Apple', 'Vegetables':'onion'}
for mykey, myval in dic.items():
print(mykey)
print(myval)
result
fruits
Apple
Vegetables
onion
value
--Elements can be retrieved with a combination of key
and index
dic_list.py
dic = {'fruits':['Apple', 'Peaches'], 'Vegetables':['onion', 'carrot']}
#Extract a list of elements from a key
for mykey in dic.keys():
for i in range(0,len(dic[mykey])):
print(dic[mykey][i])
#Directly retrieve the list of elements
for myvalue in dic.values():
for i in range(0,len(myvalue)):
print(myvalue[i])
Both have the same result
result
fruits
Apple
Vegetables
onion
--Elements can be retrieved with a combination of key
and the nested dictionary `` `key```
dic_dic.py
dic = {'fruits': {'Like':'Apple', '大Like':'Peaches'}, 'Vegetables': {'Like':'Tomato', 'Hate':'green pepper'}}
print(dic['fruits']['Like'])
print(dic['Vegetables']['Hate'])
result
Apple
green pepper