选择按索引嵌套在列表中的字典

时间:2020-07-24 20:30:08

标签: python python-3.x list dictionary

以下是列表的示例:

{'Item': 'milk', 'Price': '2.0', 'Quantity': '2'}, {'Item': 'egg', 'Price': '12.0', 'Quantity': '1'}]

这是我的代码:

def edit_items(info):
xy = info

print('Index |       Orders')
for x in enumerate(xy):
    print('\n')
    print(x)
    
choice = int(input('Which entry would you like to edit? Choose by index. :'))
print(x[choice])

Id希望用户能够按索引选择条目,并允许他们编辑字典中的信息。

到目前为止,我的代码已打印出来:

Index |       Orders


(0, {'Item': 'milk', 'Price': '2.0', 'Quantity': '2'})


(1, {'Item': 'egg', 'Price': '12.0', 'Quantity': '1'})

但是我不知道如何选择一个,将其分配给一个变量,并能够编辑其中的内容。

干杯。 Nalpak _

2 个答案:

答案 0 :(得分:0)

如果要编辑词典中的项目,则可以通过按键访问它来轻松地完成它。

首先,我们设置数据

xy = [{'Item': 'milk', 'Price': '2.0', 'Quantity': '2'}, {'Item': 'egg', 'Price': '12.0', 'Quantity': '1'}]

然后,如果我对您的理解正确,那么此edit_items方法将完全满足您的需求:

def edit_items(i):
    name = input('Type in a new item name: ')
    xy[i]['Item'] = name  # 'Item' is the key.

其他几乎都一样:

print('Index |       Orders')
for x in enumerate(xy):
    print('\n')
    print(x)

choice = int(input('Which entry would you like to edit? Choose by index. :'))
print(xy[choice])
edit_items(choice)
print(xy)

如果需要,还可以使用input获取要编辑的项目的键(属性)。

答案 1 :(得分:0)

def edit_items(info):
    xy = info

    # to make multiple edits.
    while True:
        print('Index |       Orders')
        for x in range(len(xy)):
            print(x,xy[x])
    
        choice = int(input('Which entry would you like to edit?\nChoose by index: '))
        print(xy[choice])
        edit = input('What you want to edit: ')   # Key val of dict 
        value = input("Enter: ")    # Value for the specific key in dict
        xy[choice][edit] = value
        print('list updated.')
        print(xy[choice])

        more_edits = input('\nDo you want to make more edits?(y/n): ')
        if more_edits == 'n':
            break

edit_items(info)

这将帮助您进行多次编辑。