最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

Python中字典和列表的相互嵌套问题

XAMPP案例 admin 885浏览 0评论

在学习过程中遇到了很多小麻烦,所以将字典列表的循环嵌套问题,进行了个浅浅的总结分类。

  1. 列表中存储字典
  2. 字典中存储列表
  3. 字典中存储字典
  4. 易错点

首先明确:

①访问字典中的元素:dict_name[key]  /  dict_name.get(key)

②访问列表中的元素:list_name[索引]

  1. 1.列表中存储字典:

  • ①列表中存储多个字典

  1. p={‘name’:’lin’,’age’:21}
  2. y={‘name’:’xue’,’age’:20}
  3. c=[p,y]
  4. print(c)

 

  1. 输出结果:
    [{'name': 'Jonh', 'age': 18}, {'name': 'Marry', 'age': 19}]
  2. ②访问列表中字典的值

  3.  
  4.  

    输出结果:

    person's name is Jonh
    Marry's age is 19
    1. print(f”person’s name is {people[0].get(‘name’)}”)
    2. print(f”{people[1].get(‘name’)}’s age is {people[1].get(‘age’)}”)
    3. #先用person[0/1]访问列表里的元素(字典),再用get方法访问字典里的值
  5. ③遍历访问多个值

  1. for person in people:
  2. #将列表中的字典,依次赋值给person
  3. print(f”{person[‘name’]}’s age is {person[‘age’]}”)
  4. #取出每个循环里变量person(字典)的键和值

 输出结果:

Jonh's age is 18
Marry's age is 19

因为字典中有多个键值对,所以进行多层嵌套。

外层嵌套访问列表中的每个字典,内层嵌套访问每个字典元素的键值对。

  1. for person in people:
  2. #在每个遍历的字典里再进行嵌套(内层循环)
  3. for k,v in person.items():
  4. print(f”{k}:{v}”)

输出结果:

name:Jonh
age:18
name:Marry
age:19

2.字典中存储列表

①访问字典中的列表元素

先用list[索引]访问列表中的元素,用dict[key]方法访问字典中的值。

  1. favourite_places={
  2. ‘lin’:[‘beijing’,’tianjin’],
  3. ‘jing’:[‘chengdu’,’leshan’],
  4. ‘huang’:[‘shenzhen’]
  5. }
  6. #访问字典中的值可以用:dict_name[key]
  7. print(favourite_places[‘lin’])
  8. #访问列表里面的元素用索引:list_name[索引]
  9. print(favourite_places[‘lin’][0].title())

输出结果:

['beijing', 'tianjin']
Beijing

循环访问字典中列表的元素,也是要用dict_name[key]先访问字典中的值(列表)

  1. for i in favourite_places[‘lin’]:
  2. print(i.title())

 

输出结果:

Beijing
Tianjin

②访问字典中的值(字典中的值为列表)

注意:直接访问字典中的值,会以列表的形式呈现。

  1. for name,place in favourite_places.items():
  2. print(f”{name.title()}’s favourite places are {place}”)

 

 输出结果:

Lin's favourite places are ['beijing', 'tianjin']
Jing's favourite places are ['chengdu', 'leshan']
Huang's favourite places are ['shenzhen']

为了避免,要进行循环嵌套

  1. for names,places in favourite_places.items(): #对三个键值对先进行一个大循环
  2. print(f'{names.title()} favourite places are:’) #在大循环里每一组键值对开头先打印这句话
  3. for place in places: #之后再对值进行一个小循环,打印出值中的每个元素
  4. print(place.title())

 

输出结果:

Lin favourite places are:
Beijing
Tianjin
Jing favourite places are:
Chengdu
Leshan
Huang favourite places are:
Shenzhen

3.字典中存储字典

①字典中不能全部由字典元素组成,会报错。

  1. p={‘name’:’lin’,’age’:21}
  2. y={‘name’:’xue’,’age’:20}
  3. c={p,y}
  4. print(c)

 

TypeError                                 Traceback (most recent call last)
<ipython-input-46-4127ab9ea962> in <module>
      1 p={'name':'lin','age':21}
      2 y={'name':'xue','age':20}
----> 3 c={p,y}
      4 print(c)

TypeError: unhashable type: ‘dict’

②字典中的值可由字典组成

  1. users={
  2. ‘a’:{‘name’:’lin’,’age’:21},
  3. ‘b’:{‘name’:’xue’,’age’:20}
  4. }
  5. print(‘———–直接访问输出——————-‘)
  6. print(users[‘a’][‘name’],users[‘a’][‘age’])
  7. print(users[‘b’][‘name’],users[‘b’][‘age’])
  8. print(‘\n———–循环嵌套的方法输出——————-‘)
  9. for username,userinfo in users.items():
  10. print(‘\n’+username+’:’)
  11. for name,age in userinfo.items():
  12. print(name,age)

 

输出结果:

-----------直接访问输出-------------------
lin 21
xue 20

———–循环嵌套的方法输出——————-

a:
name lin
age 21

b:
name xue
age 20

 

4.容易出的小错误:

①访问顺序:

可以用dict_name[key]  /  dict_name.get(key)访问字典的值,也可以用列表索引list_name[索引]访问列表的值。但是要注意哪个在外,哪个在内,先访问外层,再访问内层,直接访问内层的会出错。

②字典的值为列表,访问的结果是输出整个列表

需要嵌套循环遍历里面的键值对。

③字典中不能全部由字典元素组成

 

转载请注明:XAMPP中文组官网 » Python中字典和列表的相互嵌套问题

您必须 登录 才能发表评论!