python 示例_带有示例的Python字典keys()方法

本文介绍了Python字典的keys()方法,该方法用于获取字典的所有键,并返回一个视图对象。当字典发生变化时,视图对象也会相应更新。通过示例展示了keys()方法的使用和效果。
摘要由CSDN通过智能技术生成

python 示例

字典keys()方法 (Dictionary keys() Method)

keys() method is used to get the all keys as a view object, this view object contains all keys of the dictionary.

keys()方法用于获取所有键作为视图对象,该视图对象包含字典的所有键。

Syntax:

句法:

    dictionary_name.keys()

Parameter(s):

参数:

  • It does not accept any parameter.

    它不接受任何参数。

Return value:

返回值:

The return type of this method is <class 'dict_keys'>, it returns the keys of the dictionary as view object.

此方法的返回类型为<class'dict_keys'> ,它将字典的键作为视图对象返回。

Example 1:

范例1:

# Python Dictionary keys() Method with Example

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# printing keys
print("keys of student dictionary...")
print(student.keys())

# printing return type of student.keys() Method
print("return type is: ", type(student.keys()))

Output

输出量

data of student dictionary...
{'course': 'B.Tech', 'roll_no': 101, 'perc': 98.5, 'name': 'Shivang'}
keys of student dictionary...
dict_keys(['course', 'roll_no', 'perc', 'name'])
return type is:  <class 'dict_keys'>

If we make any changes in the dictionary, view object will also be reflected, consider the given example,

如果我们在字典中进行任何更改,则视图对象也将得到反映,请考虑给定的示例,

Example 2:

范例2:

# Python Dictionary keys() Method with Example

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# printing keys
print("keys of student dictionary...")
print(student.keys())

# changing a value
student['roll_no'] = 999

# printing dictionary
print("data of student dictionary after update...")
print(student)

Output

输出量

data of student dictionary...
{'course': 'B.Tech', 'roll_no': 101, 'perc': 98.5, 'name': 'Shivang'}
keys of student dictionary...
dict_keys(['course', 'roll_no', 'perc', 'name'])
data of student dictionary after update...
{'course': 'B.Tech', 'roll_no': 999, 'perc': 98.5, 'name': 'Shivang'}

See the output, value of roll_no is changed.

看到输出, roll_no的值已更改。

翻译自: https://www.includehelp.com/python/dictionary-keys-method-with-example.aspx

python 示例

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值