【问题标题】:Convert a list of tuples to python dictionary without losing the order将元组列表转换为 python 字典而不丢失顺序
【发布时间】:2017-03-06 09:26:15
【问题描述】:

我尝试将元组列表转换为字典,但是当我使用 dict() 函数执行此操作时,元素的顺序发生了变化:

l = [('id', 2), ('osm_id', 3), ('sourceid', 4), ('notes', 5), ('ref', 6), ('rtenme', 7), ('ntlclass', 8), ('fclass', 9), ('numlanes', 10), ('srftpe', 11), ('srfcond', 12), ('isseasonal', 13), ('curntprac', 14), ('gnralspeed', 15), ('rdwidthm', 16), ('status', 17), ('bridge', 18), ('iso3', 19), ('country', 20), ('last_updat', 21)]

 dict_l = dict(l)
 print (dict_l)

{'fclass': 9, 'status': 17, 'isseasonal': 13, 'bridge': 18, 'sourceid': 4, 'country': 20, 'notes': 5, 'rtenme': 7, 'iso3': 19, 'last_updat': 21, 'gnralspeed': 15, 'osm_id': 3, 'srfcond': 12, 'numlanes': 10, 'srftpe': 11, 'rdwidthm': 16, 'ref': 6, 'id': 2, 'ntlclass': 8, 'curntprac': 14}

我在这里错过了什么?

我还尝试遍历元组列表并手动构建字典:

c = 0
for key, value in display_order_list_sorted:
    display_order_dict_sorted[display_order_list_sorted[c][0]] = display_order_list_sorted[c][1]
    c = c + 1

我遇到了同样的问题。

【问题讨论】:

  • Python 字典是无序的。使用OrderedDict
  • 您可能很高兴在 Python 3.6 dictionaries are ordered 中了解到这一点。目前这是一个实现细节,不应依赖它,但它最终可能会成为一个实际的语言特性。
  • 这些都是好消息。但是我们在 2.7 :)
  • Python 2 支持将在 2020 年停止,因此您最好准备好迁移到 Python 3。:)

标签: python dictionary


【解决方案1】:

Python 字典没有排序。您需要使用OrderedDict

【讨论】:

  • 如果您要给出与评论相同的答案,也许可以举个例子?
  • 是的,atm 我发布了答案,评论只包含一个我在发布前没有打开的链接。该示例在@Ari Gold 的答案中。
【解决方案2】:
from collections import OrderedDict
l = [('id', 2), ('osm_id', 3), ('sourceid', 4), ('notes', 5), ('ref', 6), ('rtenme', 7), ('ntlclass', 8), ('fclass', 9), ('numlanes', 10), ('srftpe', 11), ('srfcond', 12), ('isseasonal', 13), ('curntprac', 14), ('gnralspeed', 15), ('rdwidthm', 16), ('status', 17), ('bridge', 18), ('iso3', 19), ('country', 20), ('last_updat', 21)]

dict_l = OrderedDict(l)
print (dict_l)

【讨论】:

  • 那么这个答案是误导性的:stackoverflow.com/questions/6522446/…
  • @user1919,怎么会这样?
  • 因为我做同样的事情(将按值排序的元组列表转换为字典),但我没有得到按值排序的字典,正如这个答案所暗示的那样。
  • 这不是误导,只是不清楚。字典可以按照你喜欢的方式返回一个有序的字典,但如果你有很多条目,它只是千载难逢。它的显示方式基本上是“随机的”。
  • 由于元组中的第一个条目用作键,因此应确保该键在原始列表中不重复。否则会丢失一些信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
相关资源
最近更新 更多