【问题标题】:Python change dictionary value with values in array [duplicate]Python用数组中的值更改字典值[重复]
【发布时间】:2014-05-25 14:37:38
【问题描述】:

这是我正在使用的代码。我需要能够从列表中包含的值更改test["test1"]["test2"]["test3"] 的值。此列表可能会变得更长或更短。如果密钥不存在,我需要能够创建它。

test = {"test1": {"test2": {"test3": 1}}}

print test["test1"]["test2"]["test3"]
# prints 1

testParts = ["test1", "test2", "test3"]

test[testParts] = 2

print test["test1"]["test2"]["test3"]
# should print 2

【问题讨论】:

  • 我的回答中的技术也适用于这里;使用 reduce() 走到最里面的字典(根据需要创建额外的字典)。

标签: python arrays list python-2.7 dictionary


【解决方案1】:

当你尝试时

test[testParts] = 2

你会得到一个TypeError,因为testParts 是一个列表,它是可变的和不可散列的,因此不能用作字典键。您可以使用元组(不可变、可散列)作为键:

testParts = ("test1", "test2", "test3")
test[testParts] = 2

但这会给你

test == {('test1', 'test2', 'test3'): 2, 'test1': {'test2': {'test3': 1}}}

没有内置的方法来做你想做的事情,即“解包”testParts 到嵌套字典的键中。你可以这样做:

test["test1"]["test2"]["test3"] = 2

或者自己写一个函数来做这个。

【讨论】:

  • 谢谢,我认为这解决了我的问题。我会尽可能标记正确的答案。
  • Martijn 的链接问题的答案涵盖了“编写[ing] 一个函数来自己执行此操作”的好方法。
猜你喜欢
  • 2020-12-16
  • 1970-01-01
  • 2016-09-29
  • 2015-02-08
  • 2011-01-25
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多