第6章 字典
Posted dingdangsunny
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第6章 字典相关的知识,希望对你有一定的参考价值。
字典用花括号创建
message = {‘name‘: ‘dida‘, ‘age‘: "19"} print(message[‘age‘])
字典是一系列键-值对,可以通过键访问与之相关联的值
与键相关联的值可以是任意类型的对象
message[‘height‘] = 176#添加新的对象 del message[‘height‘]#删除字典中的对象
遍历字典
message = {‘name‘:‘dida‘, ‘age‘: "19"} for key, value in message.items(): print(" Key:" +key) print("Value:" +value)
输出
Key:name
Value:dida
Key:age
Value:19
for循环依次将每个键-值对存储到制定的两个变量中
这两个变量可以使用任何名称
注意!便利字典时,键-值对的返回顺序不一定与存储顺序相同
Python不关心键-值对的存储顺序,而只跟踪键与值之间的关联关系
如需排序需要使用sorted()函数
message = {‘name‘:‘dida‘, ‘age‘: "19"} for key in message.keys():#.keys用于提取键 #for key in message: print("Key:" +key) for value in message.values():#.values用于提取值 print("Value:" + value)
set()函数用于创建集合,集合中的元素互不相同,可用于去重
favorite_languages = {‘jen‘:‘python‘, ‘sarah‘: ‘C‘, ‘edward‘: ‘ruby‘, ‘phil‘: ‘python‘} print("The following languages have been mentioned") for value in favorite_languages.values(): print(value.title()) print(" The following languages have been mentioned") for value in set(favorite_languages.values()): print(value.title())
输出
The following languages have been mentioned
Python
C
Ruby
Python
The following languages have been mentioned
Ruby
C
Python
嵌套
python可以在列表中嵌套字典,在字典中嵌套列表,在字典中嵌套字典
users = { ‘aeinstein‘: { ‘first‘: ‘albert‘, ‘last‘: ‘einstein‘, ‘location‘: ‘princeton‘, }, ‘mcurie‘: { ‘first‘: ‘marie‘, ‘last‘: ‘curie‘, ‘location‘: ‘paris‘, }, } for username,user_info in users.items(): print(" Username:" + username) full_name = user_info[‘first‘] + " " + user_info[‘last‘] location = user_info[‘location‘] print(" Full name: " + full_name.title()) print(" Location: " + location.title())
输出
Username:aeinstein
Full name: Albert Einstein
Location: Princeton
Username:mcurie
Full name: Marie Curie
Location: Paris
以上是关于第6章 字典的主要内容,如果未能解决你的问题,请参考以下文章