简体   繁体   English

如何更新列表中的项,它是字典中键的值?

[英]How to update an item in a list that is value to a key in a dictionary?

So its something like this: 所以它是这样的:

{'golden': [1], 
'crazy': [1]}

and then probably update it to 然后可能将其更新为

{'golden': [2], 
'crazy': [2]}

I just want to know how I can access that list in the value of the dictionary and then change it from 1 to 2. 我只想知道如何访问字典值中的列表,然后将其从1更改为2。

You can access dict items even if they are lists the same way, so 即使它们是列表,您也可以访问字典项,因此

dict['golden']

returns that array. 返回该数组。 If you want to set the first item in the array to 0, you would do it the same way you would normally update list values: 如果要将数组中的第一项设置为0,则可以使用通常更新列表值的方式进行操作:
dict['golden'][0] = 2

Or append simpmly by doing 或通过添加简单
dict['golden'].append(2)

If you never add to that list though, it doesn't make sense for your dict to be list objects, it might as well just be an integer 如果您从不添加该列表,那么将dict用作列表对象就没有意义,它也可能只是整数

You can do something like this: 您可以执行以下操作:

your_dict['golden'][0] += 1
your_dict['crazy'][0] += 1

暂无
暂无

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

相关问题 如何使用列表项寻址字典键并附加相应的值 - How to use a list item to address a dictionary key and append the respective value 如何获取字典键列表中第二项的最低值? - How to get the lowest value of second item in key list of dictionary? 更新列表,该列表是字典中键的值 - Update a list which is a value to a key in a dictionary 如果字典的值是一个列表,有没有办法更新字典中键的值? - Is there a way to update the value of a key in a dictionary, if the value of the dictionary is a list? 如何通过使用列表的索引作为键和列表的项作为值来将列表添加到字典? - How to add list to dictionary by using index of list as key and item of list as value? 如何更新字典列表中的值 - How to update a value on a dictionary list 如何将列表中的第一项设置为字典键,并将以下项设置为该键的值? - How to set the first item in a list to a dictionary key, and the following items as the value for that key? 如何从键与列表中的项目匹配的字典中删除键值对? - How to remove key-value pairs from a dictionary where the key matches an item in a list? 将列表项与字典键进行比较,如果该项存在于字典中,则打印出键的值 - Compare list item with a dictionary key and print out the value of the key if the item exists in the dictionary 如果特定键项在字典中,如何获取列表中字典的索引 - How to get the index of a dictionary inside list if a specific key item is in the dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM