Python中的Dictionary方法| Set 1(cmp()、len()、items()…)

Python字典的基础知识已经在下面的文章中讨论过了

null

词典

本文讨论了一些字典方法。

1.str(dic) :-此方法用于 返回字符串 ,表示所有字典键及其值。

2.项目() :-此方法用于 返回列表 所有带值的字典键。

# Python code to demonstrate working of
# str() and items()
# Initializing dictionary
dic = { 'Name' : 'Nandini' , 'Age' : 19 }
# using str() to display dic as string
print ( "The constituents of dictionary as string are : " )
print ( str (dic))
# using str() to display dic as list
print ( "The constituents of dictionary as list are : " )
print (dic.items())


输出:

The constituents of dictionary as string are : 
{'Name': 'Nandini', 'Age': 19}
The constituents of dictionary as list are : 
dict_items([('Name', 'Nandini'), ('Age', 19)])

3.len() :-它返回 关键实体的计数 字典中的元素。

4.类型() :-这个功能 返回数据类型 这是争论的焦点。

# Python code to demonstrate working of
# len() and type()
# Initializing dictionary
dic = { 'Name' : 'Nandini' , 'Age' : 19 , 'ID' : 2541997 }
# Initializing list
li = [ 1 , 3 , 5 , 6 ]
# using len() to display dic size
print ( "The size of dic is : " ,end = "")
print ( len (dic))
# using type() to display data type
print ( "The data type of dic is : " ,end = "")
print ( type (dic))
# using type() to display data type
print ( "The data type of li is : " ,end = "")
print ( type (li))


输出:

The size of dic is : 3
The data type of dic is : 
The data type of li is : 

5.复印件 :-此函数创建 这本词典的浅显版本 输入另一本字典。

6.明确 :-此函数用于 清理字典 目录

# Python code to demonstrate working of
# clear() and copy()
# Initializing dictionary
dic1 = { 'Name' : 'Nandini' , 'Age' : 19 }
# Initializing dictionary
dic3 = {}
# using copy() to make shallow copy of dictionary
dic3 = dic1.copy()
# printing new dictionary
print ( "The new copied dictionary is : " )
print (dic3.items())
# clearing the dictionary
dic1.clear()
# printing cleared dictionary
print ( "The contents of deleted dictionary is : " ,end = "")
print (dic1.items())


输出:

The new copied dictionary is : 
dict_items([('Age', 19), ('Name', 'Nandini')])
The contents of deleted dictionary is : dict_items([])

本文由 曼吉星 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享