Skip to main content
 首页 » 编程设计

python OrderedDict更新具有相同值的键列表

2025年05月04日16zhenyulu

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

for idx in indexes: 
    res_dict[idx] = value 

其中 value 是一个 int 变量,indexes 是 int 的 list >s,作为键,res_dict是一个OrderedDict,试图在一行中解决上面的问题,

res_dict[indexes]=value 

但出现错误:

TypeError: unhashable type: 'list' 

循环或列表推导是执行此更新的唯一方法吗?

请您参考如下方法:

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

做您想做的事情的最pythonic方式是:

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

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