简体   繁体   English

替换字典内列表中的特定索引?

[英]Replace specific index in list inside dictionary?

how to replace specific index in list inside dictionary?如何替换字典内列表中的特定索引?

I have我有

dictionary = { "one" : 1, values : [2, 3, "apples", 4]}

I want to change "apples" into "pears", how do I do that?我想把“苹果”变成“梨”,我该怎么做?

There are a couple of things you can do:您可以做几件事:

  • If you know the specific index of the value you wish you replace you can simply do:如果您知道您希望替换的值的特定索引,您可以简单地执行以下操作:

     dictionary['values'][2] = "pears"
  • If the specific index is always in question but the value you wish to replace is known, you can use list.index like so:如果特定索引总是有问题但您希望替换的值是已知的,您可以使用list.index像这样:

     dictionary['values'][dictionary['values'].index('apples')] = "pears"

Also just an FYI, your dict "values" entry should be surrounded by quotes or you will get an error in this example.也只是一个仅供参考,您的 dict “values” 条目应该用引号引起来,否则在此示例中您将收到错误消息。

dictionary = { "one" : 1, "values" : [2, 3, "apples", 4]}

If you know it's always in a list but can be in different places in that list and under different keys in the dict you can use this:如果您知道它总是在一个列表中,但可以在该列表中的不同位置以及 dict 中的不同键下,您可以使用以下命令:

     def apples_to_pears(dictionary):
          for key, value in dictionary.items():
              if isinstance(value, list):
                  dictionary[key]=["pears" if i == "apples" else i for i in value]

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

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