python keys_Python dict keys()用法及代码示例

字典Python中的数据是一个无序的数据值集合,用于存储数据值(如Map),与其他仅将单个值作为元素的数据类型不同,Dictionary拥有key:value对。

Python字典中的keys()方法返回一个视图对象,该对象显示字典中所有键的列表。

用法: dict.keys()

参数:没有参数。

返回:返回一个显示所有键的视图对象。该视图对象根据字典中的更改而更改。

范例1:

# Python program to show working

# of keys in Dictionary

# Dictionary with three keys

Dictionary1 = {'A':'Geeks', 'B':'For', 'C':'Geeks'}

# Printing keys of dictionary

print(Dictionary1.keys())

# Creating empty Dictionary

empty_Dict1 = {}

# Printing keys of Empty Dictionary

print(empty_Dict1.keys())

输出:

dict_keys(['A', 'B', 'C'])

dict_keys([])

这些键值在列表中的顺序可能并不总是相同。

范例2:展示如何更新字典

# Python program to show updation

# of keys in Dictionary

# Dictionary with two keys

Dictionary1 = {'A':'Geeks', 'B':'For'}

# Printing keys of dictionary

print("Keys before Dictionary Updation:")

keys = Dictionary1.keys()

print(keys)

# adding an element to the dictionary

Dictionary1.update({'C':'Geeks'})

print('\nAfter dictionary is updated:')

print(keys)

输出:

Keys before Dictionary Updation:

dict_keys(['B', 'A'])

After dictionary is updated:

dict_keys(['B', 'A', 'C'])

在此,当更新字典时,键也会自动更新以显示更改。

实际应用:keys()可以像访问列表一样用于访问字典元素,而无需使用keys(),没有其他机制提供按索引访问字典键的方法。在下面的示例中对此进行了演示。

范例3:演示keys()的实际应用

# Python program to demonstrate

# working of keys()

# initializing dictionary

test_dict = { "geeks" :7, "for" :1, "geeks" :2 }

# accessing 2nd element using naive method

# using loop

j = 0

for i in test_dict:

if(j==1):

print ('2nd key using loop:' + i)

j = j + 1

# accessing 2nd element using keys()

print ('2nd key using keys():' + test_dict.keys()[1])

输出:

2nd key using loop:for

2nd key using keys():for

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值