【问题标题】:How to append multiple values in the same key in Python 3?如何在 Python 3 中的同一个键中附加多个值?
【发布时间】:2019-03-01 22:37:06
【问题描述】:

与我见过的例子不同,我认为我的例子有点不同,到目前为止还没有找到任何可以帮助我的例子。所以在这里我再次寻求帮助。现在已经为此工作了大约 3 天,我在 Python 3 中有点新,所以请多多包涵。谢谢。

到目前为止,我得到的字典是这样的:

{0: 'fruits', 1: 'veggies', 2: 'drinks'}

我希望是这样的:

{'fruits' : { 'apple', 'orange'}, 'veggies' : { 'cucumber','eggplant'}, 'drinks' : {'coke','juice'}}

我一直在尝试将其他(或多个)值附加到同一个键,但没有任何效果。似乎很难将值附加到字典中的键。在我不断尝试的同时,我还不如在线寻求帮助。

这是我的代码:

# MODULES
import os

# FUNCTIONS


def clear():
    os.system('cls')


def skip():
    input("<Press Enter To Continue>")


def createINV():
    clear()
    invdict = {}
    invname = {}

    countinv = int(input("Enter the number of Inventories: "))

    for a in range(countinv):

        # ADD LISTS HERE
        addinv = str(input("Enter Inventory #%d: " % (a+1)))
        invdict[a] = addinv

        print(invdict)
    for b in range(countinv):
        countitem = int(input("\nHow many items in %r inventory: " % list(invdict.values())[b]))
        for c in range(countitem):
            additem = input("Enter item #%d: " % (c+1))
            #invdict[c].extend
            #list(invdict.keys(c)[]).append(additem)
            #invdict.setdefault(c, []).append(c[additem])
            #invdict[c].append(additem)
            # d.setdefault(year, []).append(value)
    for aprint in range(countinv):
        for x,y in invdict.items():
            print (x,y)
            # for bprint in range(countitem):
            #     for y invname.value[bprint]:
            #         print(y)    


# START - Welcome
clear()
print("Hi! Welcome to Python Inventory System.")
skip()
clear()

# START - Introduction
print("This is an Inventory System where you can input any Inventoriesyou want and how many you want.")
print("For e.g.: You can input 3 types of Inventories such as Vegetables, Fast Foods, Drinks, etc.")
print("And you can input the prices for each item.")
skip()
clear()


# COMMENCE PROGRAM
x = 0
while x != 1:
    start = input("Are you ready to Start? (Y/N):")
    if start == 'y' or start == 'Y':
        x += 1
        createINV()

    elif start == 'n' or start == 'N':
        x += 1
        clear()

    else:
        x = 0

【问题讨论】:

  • 查看collections.defaultdict(set)
  • 也许您可以使用dictionaryset 作为值

标签: python python-3.x dictionary append key-value


【解决方案1】:

要得到你想要的,你应该修改函数createINV()。确切地说,您应该修改存储数据的方式。

def createINV():
    clear()

    # one dictionary to store all the data
    # keys are inventories
    # values are sets of items
    invdict = dict()

    countinv = int(input("Enter the number of Inventories: "))

    for a in range(countinv):
        addinv = input("Enter Inventory #%d: " % (a+1))
        # initialize key-value pairs
        invdict[addinv] = set()

    # iterate over inventories
    for inv in invdict:
        countitem = int(input("\nHow many items in %s inventory: " % inv))
        for c in range(countitem):
            additem = input("Enter item #%d: " % (c+1))
            # add item to appropriate inventory
            invdict[inv].add(additem)

    print('\nYour inventory:')
    print(invdict)

输出:

Enter the number of Inventories: 3
Enter Inventory #1: qwe
Enter Inventory #2: asd
Enter Inventory #3: zxc

How many items in qwe inventory: 1
Enter item #1: rty

How many items in asd inventory: 2
Enter item #1: fgh
Enter item #2: jkl

How many items in zxc inventory: 3
Enter item #1: vbn
Enter item #2: m,.
Enter item #3: ///

Your inventory:
{'qwe': {'rty'}, 'asd': {'jkl', 'fgh'}, 'zxc': {'vbn', 'm,.', '///'}}

【讨论】:

  • 你在 30 分钟内编写了我试图制作 3 天的程序。我不会复制粘贴所有代码,感觉就像我在欺骗自己,但我只会使用我需要的代码来更正自己的代码。非常感谢!
  • 我还想补充一下您编写代码的整洁程度。天哪,我感觉好虚弱。
  • 我错过了 'set()' 函数。我在谷歌上找到的所有示例中都没有看到它。我将通过增加每个项目的价格来进一步推进这个程序。几天后会再次见到你们(我希望不会)。谢谢!
  • set() 不是函数而是数据类型,在继续之前,您应该了解它与 list 的区别
猜你喜欢
  • 2019-04-27
  • 1970-01-01
  • 2015-02-16
  • 2017-09-07
  • 1970-01-01
  • 2016-04-04
  • 2021-05-09
  • 2023-03-11
  • 2020-03-06
相关资源
最近更新 更多