A dictionary in Python is a collection of key-value pairs.
alien = {}
alien['color'] = 'green' # 新增
alien['speed'] = 'fast'
alien[5] = 'hello' # 可以是数字
alien['color'] = 'red' # 修改
del alien['speed'] # 删除
print(alien)
用[]访问字典值,如果不存在则会报错,可以用get()方法,第一个参数为要获取的键,第二个参数为键值不存在时返回的默认值,如果不给第二个参数,返回None
polls = {
'Lily': 'Python',
'Judy': 'Java',
'cathy': 'JS',
}
poll = polls.get('andy', 'not found')
print(poll)
loop through a dictionary
polls = {
'lily': 'Python',
'judy': 'Java',
'cathy': 'JS',
'andy': 'Python',
'caven': 'C',
}
# 遍历键值对
for key,value in polls.items():
print(f"{key}'s favorite language is {value}")
# 只遍历key, keys()得到由key组成的数组
for key in polls.keys():
print(key)
# key排序
for key in sorted(polls.keys()):
print(key)
# 与上面等价,默认是遍历key
for key in polls:
print(key)
# 遍历值
for value in polls.values():
print(value)
# value去重, set不允许存储重复值
for value in set(polls.values()):
print(value)
# 声明一个set
a_set = {'cat', 'dog', 'cow', 'horse'}