一、dict 的基本用法
二、如何获取嵌套中的 value
三、如何获取 list 和 dict 中 key 的个数
spam = ['cats', 'dogs', 'moose']
bacon = ['dogs', 'moose', 'cats']
eggs = {'name': 'Zophie', 'species': 'cat', 'age': 8}
eggs1 = {“size”: 24}
# update
eggs.update(eggs1)
return(eggs)
'''
{'name': 'Zophie', 'species': 'cat', 'age': 8, 'size':24}
'''
# 获取name的value
print(eggs['name'])
# 使用get方法,返回key键的value
print('存在key键'+str(eggs.get('name', 0)))
print('不存在key键'+eggs.get('apple', '0'))
# 使用setdefault 方法,存在key值,则显示字典中的值,不存在,则添加到字典中,并显示设置的值
print(eggs.setdefault('ages', 12))
print(eggs)
# 获取list
print(list(zip(eggs))[1])
# 获取eggs的values
for v in eggs.values():
print(v)
# 获取eggs的key
for k in eggs.keys():
print(k)
# 元组的方式获取eggs
for k, v in eggs.items():
print(k, v)
for i in eggs.items():
print(i)
# 列表的方式返回
eggs.items()
# 生成器(迭代器)方式返回
x = eggs.iteritems()
list(x)
# 获取嵌套字典中的value
allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
'Bob': {'ham sandwiches': 3, 'apples': 2},
'Carol': {'cups': 3, 'apple pies': 1}}
def totalBrought(guests, item):
numBrought = 0
for k, v in guests.items():
numBrought = numBrought + v.get(item, 0)
return numBrought
print('Number of things being brought:')
print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
thing = {'ben': 'red'}
if 'color' not in thing:
thing['color'] = 'black'
print(thing)
# 简写方式
print(thing.setdefault('color', 'black'))
# get 方法不会写入dict中,若存在image显示dict中的value,不存在则返回black
print(thing.get('image', 'black'))
print(thing)
# 获取dict和list中gold coin的总数
a= ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
b= {'gold coin': 42, 'rope': 1}
# 获取a中gold coin的number
def A(a):
result = 0
for num in a:
if num == 'gold coin':
result += 1
return result
# print(A(a))
# 获取b中gold coin的个数
def addToB(b):
for k, v in b.items():
if k == 'gold coin':
print(v)
result = v+A(a)
return result
print(addToB(b))
# 使用get方法获取b中gold coin个数
gold_coin = b.get('gold coin', 0)
print(gold_coin)
print(A(a)+gold_coin)
有更好的方法,请指出