Python---嵌套

it2022-05-06  7

字典与列表、列表与字典、字典与字典的嵌套

示例程序:

# -*- coding: utf-8 -*- """ Created on Sun Jul 28 19:03:33 2019 @author: cenxi """ #字典、列表嵌套 #字典列表 user_1={ 'first_name':'Jain', 'last_name':'Grade', 'age':18, 'city':'California', } user_2={ 'first_name':'Hellen', 'last_name':'James', 'age':19, 'city':'Washington', } user_3={ 'first_name':'Alice', 'last_name':'Yerk', 'age':20, 'city':'Florida', } people=[user_1,user_2, user_3] for pl in people: print(pl) #列表-字典 favorite_places={ 'Jain':['Japan','America'], 'Alice':['China','America','Japan'], 'Hellen':['China','Australia'], } for name,places in favorite_places.items(): where='' for place in places: where +=' ' where += place print(name+"'s favorite places are "+ where + '.') #字典-字典 cities={ 'Xian':{'country':'China', 'population':'15', 'fact':':socialist',}, 'Chengdu':{'country':'China', 'population':':15', 'fact':':socialist',}, 'Shanghai':{'country':'China', 'population':':20', 'fact':':socialist',}, } for key,values in cities.items(): for key_1,values_1 in values.items(): print(key+"'s "+key_1+': '+values_1)

运行结果:

{'first_name': 'Jain', 'last_name': 'Grade', 'age': 18, 'city': 'California'} {'first_name': 'Hellen', 'last_name': 'James', 'age': 19, 'city': 'Washington'} {'first_name': 'Alice', 'last_name': 'Yerk', 'age': 20, 'city': 'Florida'} Jain's favorite places are Japan America. Alice's favorite places are China America Japan. Hellen's favorite places are China Australia. Xian's country: China Xian's population: 15 Xian's fact: :socialist Chengdu's country: China Chengdu's population: :15 Chengdu's fact: :socialist Shanghai's country: China Shanghai's population: :20 Shanghai's fact: :socialist

最新回复(0)