简体   繁体   English

Python:将项目添加为列表,该列表是字典中的值

[英]Python: Adding an item a list which is a value in a dictionary

I can't figure out how to add certain values to a list for each individual key. 我不知道如何为每个单独的键添加某些值到列表中。 I have a few types (b,m,t,d,c) which are the keys, and then I want to add costs of those items to a list that is the value of the dictionary each time I go through the loop. 我有几种类型(b,m,t,d,c)作为键,然后我想将这些项目的成本添加到列表中,该列表是每次循环时字典的值。 This is what I have so far: 这是我到目前为止的内容:

a={}
allitemcostb=[]
allitemcostm=[]
allitemcostt=[]
allitemcostd=[]
allitemcostc=[]
n=4

while n>0:
    itemtype=raw_input("enter the item type-b,m,t,d,c:")
    itemcost=input("enter the item cost:")
    if itemtype="b":    
        allitemcostb.append(itemcost)
        a[itemtype]=allitemcostb
    if itemtype="m":
        allitemcostm.append(itemcost)
        a[itemtype]=allitemcostm
    if itemtype="t":
        allitemcostt.append(itemcost)
        a[itemtype]=allitemcostt
    if itemtype="d":
        allitemcostd.append(itemcost)
        a[itemtype]=allitemcostd
    if itemtype="c":
        allitemcostc.append(itemcost)
        a[itemtype]=allitemcostc
    else:
        print "Sorry please enter a valid type"
    n=n-1
print a

It keeps giving me error messages, whether it be something isn't defined, or improper syntax. 无论是未定义的内容还是语法不正确的信息,它始终会向我显示错误消息。 Thanks 谢谢

Instead of a[itemtype] = allitemcostb , which simply sets that key's value to a new cost, you need to create a list if that key doesn't exist yet or add it to the existing list if it does. 代替a[itemtype] = allitemcostb ,它只是将该键的值设置为新成本,如果该键尚不存在,则需要创建一个list ,或者如果该键不存在,则需要将其添加到现有list中。 Do this with the setdefault() method. 使用setdefault()方法执行此操作。

The following uses just a dictionary with itemtype:[itemcost, itemcost...] and no separate list s, dispenses with the manually-incremented while loop in favor of a for loop with an xrange , and replaces the large branching structure with a more direct structure (instead of "if it's a , do a ," it does "do whatever it is"). 以下代码仅使用具有itemtype:[itemcost, itemcost...]且没有单独list s的字典,省去了手动递增的while循环, while使用xrange代替了for循环,并使用了更多的替换了大分支结构直接结构(而不​​是“如果是a ,执行a ”,而是“执行所有操作”)。 The line if itemtype in ('b', 'm', 't', 'd', 'c'): checks that the entered itemtype is a single-character string representing an available option. 该行if itemtype in ('b', 'm', 't', 'd', 'c'):检查输入的itemtype是否为表示可用选项的单字符字符串。 If the entered itemcost can't be converted to a float , the error is caught and the user is prompted to try again. 如果输入的itemcost不能转换为float ,则会捕获错误,并提示用户再次尝试。

a={}
n=4

for i in xrange(n):
    itemtype = raw_input("enter the item type-b,m,t,d,c:")
    itemcost = raw_input("enter the item cost:")
    try:
        itemcost = float(itemcost)
    except ValueError:
        print "Sorry, please enter a valid cost."
        break
    if itemtype in ('b', 'm', 't', 'd', 'c'):
        a.setdefault(itemtype, []).append(itemcost)
    else:
        print "Sorry, please enter a valid type."

print a

try this: 尝试这个:

a = {}
all_item_cost_b=[]
all_item_cost_m=[]
all_item_cost_t=[]
all_item_cost_d=[]
all_item_cost_c=[]
n = 4

while n > 0:
    item_type = input("enter the item type-b,m,t,d,c:")
    item_cost = input("enter the item cost:")
    if item_type == "b":
        all_item_cost_b.append(item_cost)
        a[item_type] = all_item_cost_b
    elif item_type == "m":
        all_item_cost_m.append(item_cost)
        a[item_type] = all_item_cost_m
    elif item_type == "t":
        all_item_cost_t.append(item_cost)
        a[item_type] = all_item_cost_t
    elif item_type == "d":
        all_item_cost_d.append(item_cost)
        a[item_type] = all_item_cost_d
    elif item_type == "c":
        all_item_cost_c.append(item_cost)
        a[item_type] = all_item_cost_c
    else:
        print("Sorry please enter a valid type")
    n = n - 1
print(a)

Give us a feedback. 给我们反馈。 Don't forget to mark as answered, if this solves your problem. 如果这可以解决您的问题,请不要忘记将其标记为已回答。 Cheers. 干杯。

Here are two solutions. 这是两个解决方案。

The fist one is not so strict. 拳头不是那么严格。 it will allow the user to enter any value for the itemtype but not for the itemcost 它将允许用户为itemtype输入任何值,但不能为itemcost输入任何值

a={}
n=4

while (n>0):
    itemtype = input("enter the item type-b,m,t,d,c:")
    itemcost = input("enter the item cost:")

    while(True):
        try:
            itemcost = float(itemcost)
            break;
        except ValueError:
            print ("Sorry, please enter a valid cost.")
            itemcost = input("enter the item cost:")

    if itemtype.lower() in "b m t d c".split():
        a[itemtype] = a.get(itemtype,list())+[itemcost]

    n-=1

print (a)

This second form will be strict for both user inputs and will keep prompting till the user enters the expected value 第二种形式对于用户输入都是严格的,并且会一直提示直到用户输入期望值

a={}
n=4

while (n>0):
    itemtype = input("enter the item type-b,m,t,d,c:")
    ##user enters a wrong value
    while(itemtype.lower() not in "b m t d c".split() ):
        print ("Sorry, please enter a valid item.")
        itemtype = input("enter the item type-b,m,t,d,c:")

    itemcost = input("enter the item cost:")
    ##user enters a wrong value
    while(True):
        try:
            itemcost = float(itemcost)
            break;
        except ValueError:
            print ("Sorry, please enter a valid cost.")
            itemcost = input("enter the item cost:")

    a[itemtype] = a.get(itemtype,list())+[itemcost]

    n-=1

print (a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM