第六章——字典

170 阅读5分钟

字典是一个较为复杂的数据结构,以键值对的形式存在,但是键和值的存储又是多样的,可以是列表,字典或其他数据类型。

一个简单的字典

#一个简单的字典
#字典可存储的信息几乎不受限制
alien_0={'color':'green','points':5}
print(alien_0['color'])  
print(alien_0['points'])

图片.png

使用字典

“实践是检验真理的唯一标准”

#使用字典
#字典是一系列键值对,每个键都与一个值关联,可以使用键来访问关联的值。与键关联的值可以是数、字符串、列表和字典。
#在python中使用”{}“标识字典
#键和值之间使用”:“分隔开

#6.2.1访问字典中的值
#获取与键想关联的值,可以依次指定字典名和放在方括号内的值
alien_0={'color':'green'}
print(alien_0['color'])

alien_0={'color':'green','points':5}
new_points=alien_0['points']
print(f"You just earned {new_points} points!")

#6.2.2添加键值对
#字典是一个动态结构,可以随时添加键值对。依次指定字典名、使用方括号括起的键和相关的值
alien_0={'color':'green','points':5}
print(alien_0)
alien_0['x_position']=0  #添加x坐标
alien_0['y_position']=25  #添加y坐标
print(alien_0)

#6.2.3 先创建一个空字典
#在空字典中添加键值对
alien_0={}
alien_0['color']='green'
alien_0['points']=5
print(alien_0)

#6.2.4 修改字典中的值
#可以依次指定字典名、用方括号括起的键,以及与该键关联的新值
alien_0={'color':'green'}
print(f"The alien is {alien_0['color']}.")

alien_0['color']='yellow'
print(f"The alien is now {alien_0['color']}.")

alien_0={'x_position':0,'y_position':25,'speed':'medium'}
print(f"Original position:{alien_0['x_position']}")
#向右移动
#根据当前速度,移动多远
if alien_0['speed']=='slow':
    x_increment=1
elif alien_0['speed']=='medium':
    x_increment=2
else:#移速很快
    x_increment=3
alien_0['x_position']+=x_increment
print(f"New position :{alien_0['x_position']}")

#6.2.5 删除键值对
#可以使用del语句将相应的键值对彻底删除,使用del语句时,必须指定字典名和要删除的键
alien_0={'color':'green','points':5}
print(alien_0)

del alien_0['points']
print(alien_0)


#6.2.6 由类似对象组成的字典
#字典可以存储一个人的多种信息,也可以存储多个人的同一种信息
favorite_languages={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}

language=favorite_languages['sarah'].title()
print(f"Sarah`s favorite language is {language}.")

#6.2.7使用Get来访问值
alien_0={'color':'green','speed':'slow'}
#print(alien_0['points'])
point_value=(alien_0.get('points','No point value assigned.'))
print(point_value)

#test
persion={'first_name':'R','last_name':'hp','age':23,'city':'xian'}
print(persion)

love_number={'rhp':14,'aaa':0,'bbb':23,'kkk':18,'hhh':20}
for number in love_number:
    print(f"{number} is love {love_number[number]}!")

kills={"oop":"面向对象","RPC":"微服务","FAUST":"api调用风格",'云原生':"flink"}
for kill in kills:
    print(f"{kill} : {kills.get(kill)}")

图片.png

遍历字典

遍历字典个人觉得是有难度的,存进去很容易,但是要拿的出来,会一层层的“拨”。

#遍历字典
#python可以遍历所有的键值对,也可以仅遍历键或值

#6.3.1 遍历所有键值对
user_0={
    'username':'efermi',
    'first':'enrico',
    'last':'fermi',
}
#使用for循环遍历字典
for key,value in user_0.items():
    print(f"\nKey:{key}")
    print(f"Value:{value}")
#简单命名
for k,v in user_0.items():
    print(f"\n{k},{v}")

favorite_languages={
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
for name ,language in favorite_languages.items():
    print(f"{name.title()}`s favorite language is {language.title()}.")

#6.3.2 遍历字典中的所有键
for name in favorite_languages.keys():
    print(name.title())
#遍历字典时,会默认遍历所有的键、
for name in favorite_languages:
    print(name.title())
for name in favorite_languages.keys():
    print(name.title())

friends=['phil','sarah']
for name in favorite_languages.keys():
    print(f"Hi {name.title()}")
    if name in friends:
        language=favorite_languages[name].title()
        print(f"\n{name.title()},I see you love {language}!")

if 'erin' not in favorite_languages.keys():
    print("Erin,please take our poll!")

#6.3.3 按照特定顺序遍历字典中所有的键
for name in sorted(favorite_languages.keys()):
    print(f"{name.title()},thank you for taking the poll.")

#6.3.4遍历字典中所有的值
print("The following languages have been mentioned:")
for language in favorite_languages.values():
    print(language.title())

#为了去重,可以使用集合(set),集合中的每个元素都时独一无二的。
print("The flowing languages have been mentioned:")
for language in set(favorite_languages.values()):
    print(language.title())

#Test
for n,v in favorite_languages.items():
    print(f"{n},{v}")

favorite_languages['number']='数字'
favorite_languages[ 'liet']='列表'
favorite_languages[ 'dict']='字典'
favorite_languages[ 'for']='循环'
favorite_languages[ '[]']='元组'
print(favorite_languages)
for k,v in favorite_languages.items():
    print(f"{k},{v}")

rivers={'nile':'egypt','sss':'daa','www':'ffff'}
for river in rivers:
   print(f"{river} runs through {rivers.get(river)}")

图片.png

图片.png

图片.png

嵌套

这才是重中之重,各种数据结构的组合,键值对的多样化处理才是字典的强大之处。

#将列表存储在字典中,或将字典存在列表中
#6.4.1 字典列表
alien_0={'color':'green','points':5}
alien_1={'color':'yellow','points':10}
alien_2={'color':'red','points':15}

aliens=[alien_0,alien_1,alien_2]
for aline in aliens:
    print(aline)

#创建一个用于存储字典的列表
aliens=[]
#使用for循环创建字典
for aline_number in range(30):
    new_alien={'color':'green','points':5,'speed':'slow'}
    aliens.append(new_alien) #添加元素

#显示前5个
for alien in aliens[:5]:
    print(alien)
print("...")
#显示有多少数据
print(f" Total number of aliens:{len(aliens)}")

#更改前3个的数值
for alien in aliens[:3]:
    if alien['color']=='green':
        alien['color']='yellow'
        alien['speed']='medium'
        alien['points']=10

#显示前5个值
for alien in aliens[:5]:
    print(alien)
print("...")

#黄色改红色 速度快 值==15
for alien in aliens:
    if alien['color']=='yellow':
        alien['color']='red'
        alien['speed']='fast'
        alien['points']=15
    elif alien['color']=='green':
        alien['color']='yellow'
        alien['speed']='medium'
        alien['points']=10

print(aliens[:10])

#在字典中存储列表
pizza={
    'crust':'thick',
    'toppings':['mushrooms','extra cheese'],
}
print(f"You orderd a {pizza['crust']}-crust pizza""with the following toppings:")

for topping in pizza['toppings']: #直接在这里就开始列表的遍历
    print(f"\t+{topping}")

favorite_languages={
    'jen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskell']
}
for name,languages in favorite_languages.items():
    print(f"\n{name.title()}`s favorite languages are:")
    if(len(languages)==1):
        print(languages[0])
        continue
    for language in languages:
        print(f"\t{language.title()}")

print(favorite_languages)

#6.4.3 在字典中存储字典
users={
    'aeinstein':{
        'first':'albert',
        'last':'einstein',
        'location':'princeton'
    },
    'mcurie':{
        'first':'marie',
        'last':'curie',
        'location':'paris'
    }
}

print(users)
for username,user_info in users.items():
    print(f"\nUsername:{username}")
    full_name=f"{user_info['first']}, {user_info['last']}"
    loaction=user_info['location']

    print(f"\t Full name:{full_name.title()}")
    print(f"\t Location:{loaction.title()}")

#Test
peoples={
    'aaa':{
        'name':'aaa',
        'age':16,
        'language':'python'
    },
    'bbb':{
        'name':'bbb',
        'age':20,
        'language':'java'
    },
    'ccc':{
        'name':'ccc',
        'age':30,
        'language':'php'
    }
}

for person in peoples.items():
    for man in person:
        print(man)

pet1={'type':'dog','owner':'aaa'}
pet2={'type':'cat','owner':'bbb'}
pet3={'type':'pig','owner':'ccc'}
pets={'pet1':pet1,'pet2':pet2,'pet3':pet3}

print(pets)
for pet,information in pets.items():
   print(f"pet={pet},information={information}")
   for seg in information.values():
       print(seg)

favorite_places={
    'aaa':['a1','a2','a3'],
    'bbb':['b1','b2','b3'],
    'ccc':['c1','c2','c3']
}
print(favorite_places)

for person in favorite_places:
    for place in favorite_places[person]:
        print(place)

cities={
    'shanaghai':{
        'persion':2000,
        'city':'china',
        'story':'old_shanghai'
    },
    'beijin':{
        'persion':5000,
        'city':'china',
        'story':'tiananmen'
    },
    'newyourk':{
        'persion':'?',
        'city':'usa',
        'story':'.....'
    }
}
for city in cities:
    print(cities[city])
    for image in cities[city]:
        print(cities[city][image])

图片.png

图片.png

图片.png

图片.png

字典的用处是多种多样的,强大的数据存储能力,键值映射关系,都需要多加理解,勤加练习。会砸后续的学习中多加理解和实践。