1.list 中嵌套 dict
1.创建
a={'a1': 1,'a2':2,'a3':3}
b={'a1': 4,'b2':5,'b3':6}
c={'a1': 7,'c2':8,'c3':9}
list=[a,b,c]
2.读取指定位置的值
l_list[0]['a1'] 0 {第一个dict} ['a1']{key值}
2. 读取相同key值 返回列表
2.dict 中嵌套 list
1.创建{,,} 不同键值 可以用for循环 d['']=[]
2.一键多值
3.dict 中key值不可重复
dict 中没有append list 有
1.list 中嵌套 dict
#1.创建[{},{}]
a = {'a1': 1, 'a2': 2, 'a3': 3}
b = {'a1': 4, 'b2': 5, 'b3': 6}
c = {'a1': 7, 'c2': 8, 'c3': 9}
l_list = [a, b, c]
#2.读取单个
rc=l_list[0]['a1']
# 3.读取相同key值 返回列表 dict[key][index]
rcs=[]
m_size=len(l_list)
for i in range(m_size):
temp=l_list[i]['a1']
rcs.append(temp)
print(rcs)
#1.创建{,,} 不同键值 可以用for循环 d['']=[]
list_key=['a1', 'a2','a3','b1','b2','b3','c1','c2','c3']
list_value=np.arange(1,10)#[1,2....9]
m_size=len(list_value)
d={}
for i in range(m_size):
d[list_key[i]]=list_value[i]
print(d)
2.dict 中嵌套 list
#2.一键多值
list_key = ['a1', 'a2', 'a3', 'a1', 'b2', 'b3', 'a1', 'c2', 'c3']
list_value = np.arange(1, 10) #[1,2....9]
m_size = len(list_value)
d = {}
for temp_key, temp_value in zip(list_key,list_value):
if temp_key not in d.keys():
d[temp_key]=temp_value
else: #已经有key了
d[temp_key]=[d[temp_key]] #置多值键名 已经dict->list
print(type(d[temp_key]))
d[temp_key].append(temp_value) #添加值
print(d)
"""
输出
{'a1': [[1, 4], 7], 'a2': 2, 'a3': 3, 'b2': 5, 'b3': 6, 'c2': 8, 'c3': 9}
如果去掉 d[temp_key]=[d[temp_key]] 其实是会出错的
d["a"]=10
d["a"].append(1) #想把值变为 [10,1]这样写是错误的。 因为 dict 没有append,list有
"""
3.dict 中key值不可重复
dict 中没有append list 有
Message = [[2, 'Mike'], [1, 'Jone'], [2, 'Marry']]
dict1 = {}
for number in Message:
value = number[0]
if value not in dict1.keys():
dict1[value] = [number]
else:
dict1[value].append(number)
print(dict1)
"""
{2: [[2, 'Mike'], [2, 'Marry']], 1: [[1, 'Jone']]}
"""