标签:OWIN one 提取 嵌套 lang cat last 创建 values
字典用花括号创建
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("\nKey:" +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("\nThe 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("\nUsername:" + username) full_name = user_info[‘first‘] + " " + user_info[‘last‘] location = user_info[‘location‘] print("\tFull name: " + full_name.title()) print("\tLocation: " + location.title())
输出
Username:aeinstein
Full name: Albert Einstein
Location: Princeton
Username:mcurie
Full name: Marie Curie
Location: Paris
标签:OWIN one 提取 嵌套 lang cat last 创建 values
原文地址:https://www.cnblogs.com/dingdangsunny/p/12250309.html