python 字典

 

1、定义字典

alien_0 = {'color': 'green', 'points': 5}

dict()创建字典

复制代码
# 创建空字典
e = dict()
print (e)
# 打印 {}
 
# 使用dict指定关键字参数创建字典,key不允许使用表达式
f = dict(k1 = 1,k2 = 'v2')
print (f)
# 打印 {'k1': 1, 'k2': 'v2'}
 
# 使用dict指定关键字参数创建字典,key使用表达式
y = dict(1=1,2=2)
# 报错:SyntaxError: keyword can't be an expression
 
# 创建两个键值对字典
h1 = [('k1',1),('k2',2)]
h = dict(h1)
print (h1)
# 打印 {'k1': 1, 'k2': 2}
 
# 创建三个键值对字典
i1 = [['j1',1],['j2',2],['j3',3]]
i = dict(i1)
print (i)
# 打印 {'j1': 1, 'j2': 2, 'j3': 3}
复制代码

 

2、访问字典中的值

复制代码
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])


lien_0 = {'color': 'green', 'points': 5}

new_points = alien_0['points']

print(f"You just earned {new_points} points!")

复制代码

 

3、添加字典键值对

复制代码
alien_0 = {
      'color' : 'green', 
      'points': 5,

} print(alien_0) alien_0['x_position'] = 0 alien_0['y_position'] = 25 print(alien_0)

alien_0 = {
      'color'     : 'green', 
      'points'    : 5,
      'x_position'  : 0,
    'y_position'  : 25,

}
复制代码

 

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']}.")

 

5、删除字典中的键值对del  、popitem()

5.1del删除后会永远消失

alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points'] print(alien_0)

 5.2popitem()  用于随机删除字典中的一个键值对,实际上字典的popitem()方法总是弹出底层存储的最后一个键值对

people = dict(a='1', b=2, c=3, d=4, e=5, f=6)

print(people)
people.popitem()
print(people)

 

 

6、适用get()来访问值

  使用放在方括号内的键从字典中获取感兴趣的值时,可能会引发问题:如果指定的键不存在就会出错

  get()的第一个参数用于指定键,是必不可少的;第二个参数为指定的键不存在时要返回的值,是可选的

复制代码
alien_0 = {'color': 'green', 'speed': 'slow'}
print(alien_0['points'])

这将导致Python显示traceback,指出存在键值错误(KeyError):

Traceback (most recent call last):
File "alien_no_points.py", line 2, in <module>
print(alien_0['points'])
KeyError: 'points'

 
复制代码

get()的第一个参数用于指定键,是必不可少的;第二个参数为指定的键不存在时要返回的值,是可选的

复制代码
alien_0 = {'color': 'green', 'speed': 'slow'}

point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)

输出 No point value assigned.


alien_0 = {'color': 'green', 'points': 5}
print(alien_0.get('name', '没有这个键~!'))

 

 
复制代码

 

7、遍历字典

7.1遍历字典中的所有键值对

复制代码
user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
}

for key, value in user_0.items():
    print(f"\nKey: {key}")
    print(f"Value: {value}")

# 或者
for k, v in user_0.items():
    pass
复制代码

 

在循环中使用变量name和language,而不是key和value。这让人更容易明白循环的作用:

复制代码
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()}.")
复制代码

 

7.2遍历字典中的所有键(key)

复制代码
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}

for name in favorite_languages.keys():
    print(name.title())

也可以写成隐式的,因为for默认就会遍历 key
for name in favorite_languages:
复制代码

 

这个例子,favorite_languages[name],name是key,favorite_languages[name]则标识这个key的值

复制代码
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}


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"\t{name.title()}, I see you love {language}!")
复制代码

 

8、字典嵌套列表

复制代码
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()},like script is:')
    for languages in favorite_languages[name]:
        print(f'\t{languages.title()}')


#直接在循环的变量languages中
for name, languages in favorite_languages.items(): print(f'\n{name.title()},like script is:') for language in languages: print(f'\t{language.title()}')
复制代码

如果列表中的语言只有一种则直接该表打印 格式 “ Sarah,is like C ”

复制代码
favorite_languages = {
    'jen': ['python', 'ruby'],
    'sarah': ['c'],
    'edward': ['ruby', 'go'],
    'phil': ['python', 'haskell'],
}

for name, languages in favorite_languages.items():
    if len(languages) > 1:
        print(f'\n{name.title()},like script is:')
        for language in languages:
            print(f'\t{language.title()}')
    else:
        print(f'\n{name.title()},is like {languages[0].title()}')
复制代码

 

9、字典中嵌套字典

取值输出

复制代码
users = {
    '张三': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
    },

    '李四': {
        '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()}")    #输出变量


#自己写的 for k, v in users.items(): print(f'\nUsername : {k.title()}') Full_name = f"{v['first']} {v['last']}" print(f'\tFull name: {Full_name}') print(f"\tLocation : {v['location']}")

 

 

复制代码

 

作业:列表嵌套字典,并插入字典 append() ,这个方法是列表追加项目的方法

people = [
    {
'first_name': '', 'last_name': '', 'age': 30, 'city': 'China'},     {'first_name': '', 'last_name': '', 'age': 35, 'city': 'American'},     {'first_name': '', 'last_name': '', 'age': 38, 'city': 'Japan'}, ] people.append(  { 'first_name': '', 'last_name': '', 'age': 40, 'city': ' Kore'}  )

 

作业:字典嵌套字典,并插入字典

复制代码

users = {
    '张三': {'first': 'albert',   'last': 'einstein',    'location': 'princeton', },
    '李四': {'first': 'marie',   'last': 'curie',   'location': 'paris', },
}


users['王五'] = {'first': 'wangwu', 'last': 'wangwu', 'location': 'Japan'}
复制代码

 

作业:字典嵌套字典,并给其中一个键 增加一个值 update() 

Python 字典 update() 方法用于更新字典中的键/值对,可以修改存在的键对应的值,也可以添加新的键/值对

users = {
    '张三': {'first': 'albert',   'last': 'einstein',    'location': 'princeton', },
    '李四': {'first': 'marie',    'last': 'curie',       'location': 'paris', },
}
users[
'李四'].update({'gender': 'famale'})

 

posted @   茶叶蛋蛋  阅读(29)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示