📜  Python字典方法

📅  最后修改于: 2022-05-13 01:55:28.540000             🧑  作者: Mango

Python字典方法

Python Dictionary就像一个地图,用于以键:值对的形式存储数据。 Python提供了各种内置函数来处理字典。在本文中,我们将看到Python提供的用于处理字典的所有函数的列表。

访问字典

以下函数可用于访问字典项(键和值)。

  • get():该函数返回给定键的值
  • keys():该函数返回一个视图对象,该对象按插入顺序显示字典中所有键的列表
  • values():此函数返回给定字典中所有可用值的列表
  • items():此函数返回包含所有字典键和值的列表

示例:访问字典项目。

Python3
# Python program to demonstrate working
# of dictionary copy
dic = {1:'geeks', 2:'for', 3:'geeks'}
print('original: ', dic)
 
# Accessing value for key
print(dic.get(1))
 
# Accessing keys for the dictionary
print(dic.keys())
 
# Accessing keys for the dictionary
print(dic.values())
 
# Printing all the items of the Dictionary
print(dic.items())


输出
original:  {1: 'geeks', 2: 'for', 3: 'geeks'}
geeks
dict_keys([1, 2, 3])
dict_values(['geeks', 'for', 'geeks'])
dict_items([(1, 'geeks'), (2, 'for'), (3, 'geeks')])

Python字典方法表

Functions NameDescription
clear()Removes all items from the dictionary
copy()Returns a shallow copy of the dictionary
fromkeys()Creates a dictionary from the given sequence
get()Returns the value for the given key
items()Return the list with all dictionary keys with values
keys()Returns a view object that displays a list of all the keys in the dictionary in order of insertion
pop()Returns and removes the element with the given key
popitem()Returns and removes the key-value pair from the dictionary
setdefault()Returns the value of a key if the key is in the dictionary else inserts the key with a value to the dictionary
update()Updates the dictionary with the elements from another dictionary
values()Returns a list of all the values available in a given dictionary



注意:有关Python词典的更多信息,请参阅Python词典教程。