简体   繁体   English

如何在python字典中编辑可变的键

[英]How do I edit a key in python dictionary that is variable

I am working on a code in python and relatively new at python so excuse me if the title of this post is unclear, am currently unable to figure out how to solve this issue where I have a blank dictionary我正在用 python 编写代码并且在 python 上相对较新,所以如果这篇文章的标题不清楚,请原谅我,我目前无法弄清楚如何解决这个问题,因为我有一个空白字典

Cart={}

And I have a few lines of code that adds an variable to it if selected如果选中,我有几行代码可以向其中添加一个变量

if x==1:
   Cart['Milk']=[qnty],[total],[gst],[offer]
if x==2:
   Cart['Butter']=[qnty],[total],[gst],[offer]
if x==3:
   Cart['Cookies']=[qnty],[total],[gst],[offer]

Here's the part where I am unable to figure out, I would like to now edit the qnty part of the variable but as there is no 'fix' key in the dictionary i am unsure how to do it, I tried doing it the way below but will only give me the name and qnty and removes the other key.这是我无法弄清楚的部分,我现在想编辑变量的qnty部分,但由于字典中没有“修复”键,我不确定该怎么做,我尝试按照以下方式进行但只会给我nameqnty并删除另一个键。

if y == 2:
   print(Cart)
   item=str(input('key in an item to edit: '))
   for item in Cart:
         qnty=int(input('Key in the quantity of %s you want: '%item))
         Cart=[item],[qnty]
   print(shopping_basket)

Is there a way to edit the Qnty of the item only?有没有办法只编辑项目的数量? I have also tried using list or assigning fixed key to the blank dictionary but just can't seem to work.我也尝试过使用列表或为空白字典分配固定键,但似乎无法正常工作。

Thank you in advance feel free to ask me more if clarifications is needed.预先感谢您,如果需要澄清,请随时问我更多。

Let's start with sample data in cart we have two items Cake and Milk让我们从购物车中的示例数据开始,我们有两个项目CakeMilk

cart = {}
cart['Cake'] = {'qnty': 1, 'total': 1,'gst': None, 'offer': False}
cart['Milk'] = {'qnty': 3, 'total': 3,'gst': None, 'offer': True}

If you want to change qnty , you must set its variable by receiving an input from a user or set it internally如果要更改qnty ,则必须通过接收来自用户的输入或内部设置来设置其变量

edit_item_attr = 'qnty'

Then you can ask which item to be edited, for example, Cake然后你可以询问要编辑哪个项目,例如,蛋糕

# Item Selection
item_list = cart.keys()
print(f'Please select an item to Edit from {item_list}')
edit_item_name = 'Cake'

Finally, you can update the item's data最后,您可以更新项目的数据

# Edit Method
cart.get(edit_item_name).update({edit_item_attr: 99999})

Result结果

'Cake': {'qnty': 99999, 'total': 1, 'gst': None, 'offer': False},
 'Milk': {'qnty': 3, 'total': 3, 'gst': None, 'offer': True}}

If I understood the problem correctly, the faulty line is Cart=[item],[qnty] .如果我正确理解了问题,错误的行是Cart=[item],[qnty] I guess you want to update the item to set the new quantity.我猜您想更新项目以设置新数量。 If so, you could probably do it this way:如果是这样,你可能可以这样做:

Cart[item] = (
   [qnty],
   Cart[item][1],
   Cart[item][2],
   Cart[item][3],
)

Here, you are working with tuples, which are immutable, so the best is to actually replace it completely, and just set the new value that you want在这里,您正在使用不可变的元组,因此最好是实际完全替换它,然后设置您想要的新值

Your approach is flawed...你的方法有问题...

a) you use a tuple where you probably don't want a tuple. a) 您在可能不想要元组的地方使用了元组。 Tuples are immutable.元组是不可变的。

So rather than所以而不是

Cart['Milk']= [qnty],[total],[gst],[offer]
             ^                            ^  you have invisible braces here
                                             due to the commas

you probably wanted你可能想要

Cart['Milk']=[qnty, total, gst , offer]

But that's still a strange concept, because someone reading the code and accessing the array would need to know in which order the items appear.但这仍然是一个奇怪的概念,因为阅读代码和访问数组的人需要知道项目出现的顺序。 He might easily confuse quantity with total.他可能很容易将数量与总量混淆。

We don't use arrays to store different kind of data.我们不使用数组来存储不同类型的数据。 We normally use arrays for the same kind of data.我们通常对相同类型的数据使用数组。 Semantically and type similar, not only type similar.语义上和类型相似,不仅类型相似。

Why?为什么? Well, with an array you can do things like好吧,使用数组,您可以执行以下操作

sum(array)

which is really cool if we sum up prices or lenghts or energy - as long as they have the same unit.如果我们总结价格或长度或能源,这真的很酷 - 只要它们具有相同的单位。 But in your case, what is the meaning if you calculate the sum of但在你的情况下,如果你计算总和是什么意思

sum([qnty, total, gst, offer])

Right: it's not even possible, because these things in the array have different units: no unit, currency, percentage and something.对:这甚至是不可能的,因为数组中的这些东西有不同的单位:没有单位、货币、百分比等等。

b) you want to update the quantity. b) 您想更新数量。 But you don't want to update the total?但你不想更新总数? That way, things will get cheaper with every item added to the cart.这样,每添加到购物车中的商品都会变得更便宜。 The total should not be a stored value, it should be a calculated value.总数不应是存储值,而应是计算值。

Create a class that does this for you, like创建一个为您执行此操作的类,例如

class CartEntry:
    def __init__(self, quantity, gst, offer, price):
        self.quantity = quantity
        self.gst = gst
        self.offer = offer
        self.price = price

    @property
    def total(self):
        return self.quantity * self.price  # TODO: consider special offers 

c) you have duplicate code. c) 你有重复的代码。 Do you recognize that there are lines very similar to each other?您是否认识到存在彼此非常相似的线条?

Cart['Milk']   =[qnty],[total],[gst],[offer]
Cart['Butter'] =[qnty],[total],[gst],[offer]
Cart['Cookies']=[qnty],[total],[gst],[offer]

If you work at a large shop, you will not finish programming ever if you go on like that.如果你在一家大商店工作,如果你继续这样下去,你将永远无法完成编程。 If you need a mapping from an integer to a string, use a dictionary like如果您需要从整数到字符串的映射,请使用类似的字典

names = {1:"Milk", 2:"Butter", 3:"Cookies"}

(and don't code that, but get it from a file or database instead) (不要编码,而是从文件或数据库中获取它)

That way you can do it all in one line:这样您就可以在一行中完成所有操作:

Cart[names[x]] = [qnty],[total],[gst],[offer]

d) Why store items in the cart by name? d) 为什么要按名称在购物车中存储物品? They seem to have an ID already.他们好像已经有身份证了。 Just use the ID.用身份证就行。 There's no need for the dictionary key to be human readable.字典键不需要是人类可读的。

How does all this help you?这一切对你有什么帮助? You get IDE support and it prevents bugs:您获得 IDE 支持,它可以防止错误:

IDE截图

IDE 截图 2

The method you are using creates tuples.您使用的方法创建元组。

Try this.试试这个。

Cart[ "milk" ] = [ [qnty],[total],[gst],[offer] ]

Then you can access and modify items at will.然后您可以随意访问和修改项目。

print( Cart[ "milk" ][ 0 ] )
Cart[ "milk" ][ 0 ] = [ 45 ]
print( Cart[ "milk" ][ 0 ] )

It would be better if you created dictionaries instead of lists like this.如果您创建字典而不是像这样的列表会更好。

Cart[ "milk" ] = dict( Quantity = qnty, Total = total, GST = gst, Offers = offer )

Then you could access data like so...然后你可以像这样访问数据......

print( Cart[ "milk" ][ "Total" ] )
Cart[ "milk" ][ "Total" ] = 66
print( Cart[ "milk" ][ "Total" ] )

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

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