【问题标题】:Replace Dictionary Values with Lists用列表替换字典值
【发布时间】:2019-04-07 07:06:23
【问题描述】:

对于给定的字典,一个未更改的键和一个列表(假设列表将始终具有 text-1 元素)从列表 ro 中替换字典中所有值的最简单方法是什么? p>

text = {'a': [1, 1, 0, 0, 0, 0], 'b': [0, 1, 0, 0, 1, 0], 'c': [1, 0, 0, 1, 0, 1], 'd': [1, 1, 1, 0, 0, 1]}
unchanged_key = 'a'
ro = [[1, 0, 1, 0, 1, 1], [1, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0]]

输出:

text = {'a': [1, 1, 0, 0, 0, 0], 'b': [1, 0, 1, 0, 1, 1], 'c': [1, 0, 0, 0, 1, 0], 'd': [1, 0, 0, 0, 0, 0]}

【问题讨论】:

  • 这只会给出字典中所有值的列表,对吧?
  • 普通dicts 不是有序结构。如果要强制排序,请使用元组列表。如果您想强制排序但有O(1) 查找,请使用OrderedDict

标签: python list dictionary iteration


【解决方案1】:

我假设您希望替换顺序与列表“ro”中的顺序相同。但是,如果键 'a' 出现在 dict 'text' 中间的某个地方,则它是有问题的。 您可以执行以下操作,结果如下:

text = {'a': [1, 1, 0, 0, 0, 0], 'b': [0, 1, 0, 0, 1, 0], 'c': [1, 0, 0, 1, 0, 1], 'd': [1, 1, 1, 0, 0, 1]}
unchanged_key = 'a'
ro = [[1, 0, 1, 0, 1, 1], [1, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 1]]
ind=-1
for k,v in text.items():    #iterating thru dictionary 'text'  
    if k==unchanged_key:
        pass
    else:
        ind=ind+1
        text[k]=ro[ind]    #repl;acing the values from ro

输出:('文本'字典)
{'a':[1, 1, 0, 0, 0, 0], 'b':[1, 0, 1, 0, 1, 1], 'c':[1, 0, 0, 0, 1, 0], 'd':[1, 0, 0, 0, 0, 1]}

【讨论】:

  • 我只是可以在沙箱上提出类似的东西,然后我看到你的解决方案:未更改的密钥 = 'a' r = 0 for i in text.keys(): if i == modified_key : continue text[i] = ro[r] r = r + 1 谢谢!
最近更新 更多