python - 如何编写一个将列表添加到字典的函数?

标签 python list function dictionary

这个美好社区中忙碌的程序员。

我正在尝试完成一本名为“自动化无聊的东西”的书中的任务。在这里,我尝试将此 DragonLoot[] 列表附加到 itemsSatchel{} 字典中。在将列表更改为字典后,我尝试使用此更新属性,但失败了,所以我真的不知道该怎么办。帮助!

import pprint

itemsSatchel = {'Arrow': 12,
                'Gold Coin': 42,
                'Rope': 1,
                'Torch': 6,
                'Dagger':1}

dragonLoot = ['Gold Coin',
              'Gold Coin'
              'Dagger'
              'Gold Coin',
              'Ruby']

def addToSatchel(self):
    #This part is my pain in the ___#


def displaySatchel(self):
    print("Inventory: ")
    itemsCounter = 0
    for k,v in itemsSatchel.items() :
        pprint.pprint(str(v) + ' ' + str(k))
        itemsCounter += v
    print('Total number of items: ' + str(itemsCounter))

addToSatchel({dragonLoot})

displaySatchel(itemsSatchel)

最佳答案

您还可以考虑使用collections.Counter这里。它可以从dict或项目列表更新

from collections import Counter

itemsSatchel = Counter({'Arrow': 12,
                        'Gold Coin': 42,
                        'Rope': 1,
                        'Torch': 6,
                        'Dagger':1})

dragonLoot = ['Gold Coin', ...]

def addToSatchel(items):
    itemsSatchel.update(items)

addToSatchel(dragonLoot)

关于python - 如何编写一个将列表添加到字典的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55293848/

相关文章:

python - 通过 Airflow UI 终止在远程位置运行的 Airflow 任务

python - 程序如何覆盖先前的输出行?

python - 使用 Python 和 py-postgresql 返回的查询中的空格

python - 如何比较 2 "Friends"并查看他们是否在彼此的好友列表中?

python - 将列表值分配给字典

计算文件中的字母 's' 和 'S'

Bash:将函数作为参数传递

python - 使用 SQLObject 将数据从一个 sqlite 数据库迁移到多个 SQLite 数据库

Python - 比较两个列表的值和长度

c - remove() - 调用的对象 'remove' 不是函数