【问题标题】:Change key to value of same key in other dictionary将键更改为其他字典中相同键的值
【发布时间】:2015-11-03 16:40:38
【问题描述】:

我正在寻找以下内容,但我不会得到它。我已经尝试过交换键值对,但没有奏效。

我想要获得的东西,考虑 2 个字典:

dict1 = {'a':1, 'b':20, 'c':100}
dict2 = {'a':'apple', 'b':'banana', 'c':'citrus'}

我正在寻找一本新词典:

dict3 = {'apple':1, 'banana':20, 'citrus':100}

有人可以帮助我或给我一些建议吗? (两个字典都非常大,所以首先我需要对其进行编程,使其在 dict2 中查找正确的键 - 它比 dict1 大得多,并且与 dict1 的顺序不同)。

【问题讨论】:

  • d3 = {d2[k]: d1[k] for k in d1}?他们总是有完全相同的键吗?
  • 少查找:{v: dict1[k] for k, v in dict2.items()}
  • 它们总是有相同的键。我
  • dict2 那个奇怪的东西是什么类型的? dict-list ? ^_^

标签: python python-3.x dictionary


【解决方案1】:

使用iteritems() 迭代字典的键和值。

for key, value in dict2.iteritems():
    dict3[value] = dict1[key]

对于 Python 3.x,iteritems() 已被简单地替换为 items(),它返回由 dict 支持的类似集合的视图,如 iteritems(),但更好。这在 2.7 中也可以作为 viewitems() 使用。操作 items() 将适用于 2 和 3,但在 2 中它将返回字典的 (key, value) 对的列表,这不会反映在 items() 调用之后发生的对字典的更改。如果想要 3.x 中的 2.x 行为,可以调用list(d.items())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 2020-07-06
    • 2021-07-21
    • 1970-01-01
    相关资源
    最近更新 更多