2026/1/4

4 阅读2分钟

新年第一天上班,复习了嵌套。

1. 字典列表

aliens=[]
for alien_number in range(30):
	new_alien={'color':'yellow','point':5,'speed':'slow'}
	aliens.append(new_alien)
for alien in aliens[:5]:
	print(alien)
print(f"Total number of aliens:{len(aliens)}")
# 》{'color':'yellow','point':5,'speed':'slow'}
    {'color':'yellow','point':5,'speed':'slow'}
    {'color':'yellow','point':5,'speed':'slow'}
    {'color':'yellow','point':5,'speed':'slow'}
    {'color':'yellow','point':5,'speed':'slow'}
# 》Total number of aliens:30

for alien in aliens[:3]:
	alien['color'] = 'green'
	alien['speed'] = 'medium'
	alien['point'] = 10
for alien in aliens[:5]:
	print(alien)
# 》{'color':'green','point':10,'speed':'medium'}
    {'color':'green','point':10,'speed':'medium'}
    {'color':'green','point':10,'speed':'medium'}
    {'color':'yellow','point':5,'speed':'slow'}
    {'color':'yellow','point':5,'speed':'slow'}

for alien in aliens[:5]:
	if alien['color'] == 'green':
		alien['color'] = 'black'
		alien['point'] = '8'
		alien['speed'] = 'slow'
	elif alien['color'] == 'yellow':
		alien['color'] = 'red'
		alien['point'] = '15'
		alien['speed'] = 'fast'
for alien in aliens[:5]:
	print(alien)
# 》{'color':'black','point':8,'speed':'slow'}
    {'color':'black','point':8,'speed':'slow'}
    {'color':'black','point':8,'speed':'slow'}
    {'color':'red','point':15,'speed':'fast'}
    {'color':'red','point':15,'speed':'fast'}

2.列表字典(在字典中存储列表)

pizza.py

pizza = {
	'crust': 'thick',
	'toppings: ['mushrooms','extra cheese'],
	}
print(f"You ordered a {pizza['crust']}-crust pizza"
       "with the following toppings:")
for topping in pizza['toppings']:
	print(f"\t{topping}") # 这里注意因为topping是一个列表,所有必须用花括号
# 》You ordered a thick-crust pizza with the following toppings:
    mushrooms
    extra cheese

favorite_colors.py

favorite_color = {
	'ken' : ['yellow','black'],
	'jay' : ['black','red'],
	'tim' : ['blue','white'],
	'coco' : ['yellow','green'],
	}
for name,colors in favorite_color.items():
	print(f"\n{name.title()}'s favorite colors are:")
	for color in lolors:
		print(f"\t{color}")

# 》Ken's favorite colors are:
	yellow
	black

  》Jay's favorite colors are:
	black
	red

  》Tim's favorite colors are:
	blue
	white

  》Coco's favorite colors are:
	yellow
	green

进一步改进:

favorite_color = {
	'ken' : ['yellow','black'],
	'jay' : ['black'],
	'tim' : ['blue','white'],
	'coco' : ['yellow','green'],
    'tracy' : [],
	}
for name,colors in favorite_color.items():
    if not colors:
         print(f"\n{name.title()} doesn't have a favorite color.")
    elif len(colors) == 1:
        print(f"\n{name.title()}'s favorite color is {colors[0]}.")
    else:
        print(f"\n{name.title()}'s favorite colors are:")
        for color in colors:
            print(f"\t{color}")
# 》Ken's favorite colors are:
	yellow
	black

    Jay's favorite color is black.

    Tim's favorite colors are:
	blue
	white

    Coco's favorite colors are:
	yellow
	green

    Tracy doesn't have a favorite color.#

3. 在字典中存储字典

many_users.py

users = {
	'coco' : {
		'first' : 'albert',
		'last' : 'einstein',
		'location' : 'princeton',
		},
	'mcurie' : {
		'first' : 'marie',
		'last' : 'curie',
		'location' : 'paris',
		},
	}
for username,user_info in users.items():
	print(f"\nUsername : {username}")
	full_name=f"{user_info['first']} {user_info['last']}"
	location=user_info['location']
	print(f"\tFull name: {full_name.title()}")
	print(f"\tLocation: {location.title()}")
	
	# 》Username : coco
			Full name: Albert Einstein
			Location: Princeton

        Username : mcurie
			Full name: Marie Curie
			Location: Paris

练习

favorite_places = {
    'tracy' : ['paris','newyork','shanghai'],
    'coco' : ['shanghai','tokey','beijing'],
    'menglei' : ['dali','shanghai','dongjing']
    }
for name,cities in favorite_places.items():
    print(f"\n{name.title()}'s favorite cities are :")
    for city in cities:
        print(f"\t{city.title()}")

#  》Tracy's favorite cities are :
	Paris
	Newyork
	Shanghai

    Coco's favorite cities are :
	Shanghai
	Tokey
	Beijing

   Menglei's favorite cities are :
	Dali
	Shanghai
	Dongjing