【问题标题】:python OrderedDict update a list of keys with the same valuepython OrderedDict 更新具有相同值的键列表
【发布时间】:2018-01-28 21:51:02
【问题描述】:

我正在尝试更新具有相同 int 值的 OrderedDict 的键列表,例如

for idx in indexes:
    res_dict[idx] = value

其中valueint 变量,indexesints 的list,它们充当键,res_dictOrderedDict,试图在一行中解决上述问题,

res_dict[indexes]=value

但得到了错误:

TypeError: unhashable type: 'list'

循环或列表理解是在此处进行此更新的唯一方法吗?

【问题讨论】:

  • indexes 是一个键列表?和keys 是什么?如果indexes 中有一个列表(我敢打赌有),那么请确保它没有被用作键;只是因为lists 不能用作键。
  • @Abdou indexesints 的列表,在此上下文中充当键
  • 嗯...你可以这样做res_dict.update((idx, value) for idx in indexes)...

标签: python python-3.x list dictionary ordereddictionary


【解决方案1】:

OrderedDict(以及 dict)提供方法 update 一次更新多个值。

做你想做的最pythonic的方式是:

res_dict.update((idx, value) for idx in indexes)

它将保持您OrderedDict的原始顺序。

【讨论】:

  • 如果res_dict 已经是OrderedDict,则显式的OrderedDict(...) 在这里是多余的...现有密钥将保持其顺序,并且任何新密钥都将照常插入...
【解决方案2】:

您可以在 fromkeys 创建的新 OrderedDict 基础上 update 您的 OrderedDict

fromkeys 方法允许为所有键提供默认值,因此您不需要在此处进行任何显式迭代。而且因为它使用OrderedDicts fromkeys 它也会保持你的indexes 的顺序:

>>> from collections import OrderedDict
>>> indexes = [1, 2, 3]
>>> value = 2
>>> od = OrderedDict([(0, 10), (1, 10)])
>>> od.update(OrderedDict.fromkeys(indexes, value))  # that's the interesting line
>>> od
OrderedDict([(0, 10), (1, 2), (2, 2), (3, 2)])

请注意,如果OrderedDictupdate 之前为空,您也可以使用:

>>> od = OrderedDict.fromkeys(indexes, value)
>>> od
OrderedDict([(1, 2), (2, 2), (3, 2)])

【讨论】:

  • 在我的例子中,od 首先不是空的,而是初始化了键:值对
  • 好的,那么你需要明确的.update(OrderedDict.fromkeys(indexes, value))。只是一个想法。 :)
  • res_dict.update((idx, value) for idx in indexes) 也保留了indexes 的顺序,对吧?考虑到res_dict 一开始就不是空的
  • 是的,这也保留了订单。我刚刚提到它是因为正常的dict.fromkeys 不会保持订单。请注意,无论您使用哪种方法(删除键时除外),已存在项目的顺序都将保持不变。但是如果您还使用update 添加新键,这些新键的顺序取决于传递给update 的参数的顺序。所以是的,(idx, value) for idx in indexes 也可以,但 dict.fromkeys(indexes, value){idx: value for idx in indexes} 不行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-18
  • 1970-01-01
  • 2019-11-18
  • 2022-01-18
  • 2021-07-08
  • 1970-01-01
相关资源
最近更新 更多