新手区 字典 dict 部分总结

GRUNMI · 2017年05月27日 · 最后由 GRUNMI 回复于 2017年06月02日 · 1059 次阅读

一、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)

有更好的方法,请指出😀

共收到 4 条回复 时间 点赞

补两个常用的
update()
iteritems()

kanchi240 回复

谢谢😀

获取嵌套字典中的 value,你这个目前只是针对的字典的值是数值类型的吧,

allGuests = {'Alice': {'apples': 5, 'pretzels': '12'},
             'Bob': {'ham sandwiches': 3, 'apple': 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, 'pretzels')))
报错
Traceback (most recent call last):
  File "C:/Users/Administrator/Desktop/laoshi/111.py", line 18, in <module>
    print(' - Apples ' + str(totalBrought(allGuests, 'pretzels')))
  File "C:/Users/Administrator/Desktop/laoshi/111.py", line 15, in totalBrought
    numBrought = numBrought + v.get(item, 0)
TypeError: unsupported operand type(s) for +: 'int' and 'str'  

代码不具有通用性。

雷子 回复
int(v.get(itme, 0))

谢谢啊,这样应该就可以了😃

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册