【问题标题】:Why am I getting an unwanted result while making a dictionary via list of tuples?为什么我在通过元组列表制作字典时会得到不需要的结果?
【发布时间】:2020-06-19 07:25:53
【问题描述】:
x = {'Jackie': 176, 'Wilson': 185, 'Saersha': 165,'Roman': 185,'Abram': 169}
y = [(v, k) for k, v in x.items()]  # creates a list of tuples as (value, key) pair
y.sort(reverse = True)  # sorts the items in a list
# creates a dictionary with key as value from list(x) and value as a list of key from list(x)
z = {}
for a in y:
    if a[0] in z:
        z[a[0]].append(a[1])
    else:
        z[a[0]] = [a[1]]

print(z)

输出不应该是:

{185: ['Wilson', 'Roman'], 176: ['Jackie'], 169: ['Abram'], 165: ['Saersha']}

相反,它是这样的:

{176: ['Jackie'], 185: ['Wilson', 'Roman'], 165: ['Saersha'], 169: ['Abram']} 

【问题讨论】:

  • 确定吗?不是当我执行它时......
  • 顺便检查一下 defaultdicts 这样的用例。
  • 为什么重要?在字典中排序不是问题。

标签: python dictionary tuples


【解决方案1】:

我想您使用的是旧版本的 python,其中字典不保留排序。尝试使用collections.OrderedDict 而不是dict 这将解决您的问题,因为即使在旧版本的语言和没有有序@987654323 的语言的其他实现中,数据结构也可以保证保留插入顺序@。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 2020-11-08
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    相关资源
    最近更新 更多