脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 中dict的元素取值操作

python 中dict的元素取值操作

2021-09-18 00:40Loewi大湿 Python

这篇文章主要介绍了python 中dict的元素取值操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

如下所示:

?
1
dict.get(key, default=none)

key – 字典中要查找的键。

default – 如果指定键的值不存在时,返回该默认值值。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{'1*': 9, '2*': 6, '**': 15}.values()
out[377]: dict_values([9, 6, 15])
 
{'1*': 9, '2*': 6, '**': 15}.keys()
out[378]: dict_keys(['1*', '2*', '**'])
 
{'1*': 9, '2*': 6, '**': 15}.items()
out[379]: dict_items([('1*', 9), ('2*', 6), ('**', 15)])
 
{'1*': 9, '2*': 6, '**': 15}.get('1*')
out[380]: 9
 
{'1*': 9, '2*': 6, '**': 15}.get('00','whatever')
out[381]: 'whatever'

补充:python字典键的取值和字典值的取值方法

python字典,因为字典是可变类型数据,允许对字典进行取值。

对键的取值方法,使用keys()函数。

程序实例1:

使用keys()函数取键名,并转换为列表。

?
1
2
3
4
5
dict_val = {'及时雨':"宋江",'花和尚':'鲁智深','母夜叉':'孙二娘'}
key = dict_val.keys()
print(key)
print(list(key))
print(list(key)[1])

python 中dict的元素取值操作

对字典的值进行取值操作,用values()函数。

程序实例2:

用values()函数对字典的值进行取值操作,并转化为列表。

?
1
2
3
4
5
dict_val = {'及时雨':"宋江",'花和尚':'鲁智深','母夜叉':'孙二娘'}
value = dict_val.values()
print(value)
print(list(value))
print(list(value)[1])

python 中dict的元素取值操作

对字典的元素进行取值,包括键名及其对应的值,使用items()函数。

程序实例3:

使用items()函数对字典的元素进行取值操作。

?
1
2
3
4
5
6
7
8
dict_val = {'及时雨':"宋江",'花和尚':'鲁智深','母夜叉':'孙二娘'}
item = dict_val.items()
print(item)
print(list(item))
print(list(item)[1])
key,value = list(item)[1]
print(key)
print(value)

python 中dict的元素取值操作

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/weixin_42317507/article/details/90613620

延伸 · 阅读

精彩推荐