【问题标题】:How to order my dictionary in python? [duplicate]如何在python中订购我的字典? [复制]
【发布时间】:2012-05-10 07:31:08
【问题描述】:

可能重复:
In Python, how to I iterate over a dictionary in sorted order?

我需要字典方面的帮助。我有两个字典,我想在这两个字典中添加相同键的值。我需要列出对具有相同键的值求和的列表。我做了这个列表,但是在完成所有计算后添加了它们的键是两个字典中唯一的那些值。我的意思是:

dectionary1= {8: 2, 0: 6, 2: 5, 3: 34}  
dectionary2= {8: 6, 1: 2, 3: 2}

我的清单必须是:

summing= [6, 2, 5, 36, 8]

因为它会取0并检查dectionary 2中是否有0,然后它将TAKE 1(NOT 2)并检查是否在dectionary 1中找到它以便对列表进行排序。

到目前为止我得到了这个:

summing=[8, 6, 5, 36, 2]

这里最初需要键 (8) 而不是 (0)!!我希望它井井有条。

要查看我的代码,到目前为止我得到了什么:

dic1= {8: 2, 0: 6, 2: 5, 3: 34}  
dic2= {8: 6, 1: 2, 3: 2}
p=[]
for x in dic1:
    if x in dic2:
        g=dic1[x]+dic2[x]
        p=p+[g]
    else:
        p=p+[dic1[x]]
for m in dic2:
    if m in dic1:
        p=p
    else:
        p=p+[dic2[m]]

我想如果我可以让字典升序排列会容易得多,但是如何呢?

我的 python 是 Wing IDE 3.2

谢谢

【问题讨论】:

  • common_keys = set(dic1.keys()) & set(dic2.keys())。并且 dict 元素没有排序,因此对于您的情况,没有“按顺序”之类的东西。

标签: python


【解决方案1】:

这里有两种选择,一种是使用collections.OrderedDict(),但我认为更简单的选择就是这样做:

[dic1.get(x, 0)+dic2.get(x, 0)for x in sorted(dic1.keys() | dic2.keys())]

我们首先创建一组任意键in either of the dictionariessort this into the right order,然后是loop over it with a list comprehension,将两个值相加(or 0 if the value doesn't already exist)

>>> dic1= {8: 2, 0: 6, 2: 5, 3: 34}  
>>> dic2= {8: 6, 1: 2, 3: 2}
>>> [dic1.get(x, 0)+dic2.get(x, 0)for x in sorted(dic1.keys() | dic2.keys())]
[6, 2, 5, 36, 8]

请注意,这只适用于 3.x,其中 dict.keys() 返回 set-like dictionary view。如果您想在 python 2.7.x 中执行此操作,请改用 dict.viewkeys(),在此之前,set(dict.iterkeys()) 将是最佳选择。

【讨论】:

  • 请仔细检查语法。在 Python 2.7.x 中引发TypeError: unsupported operand type(s) for |: 'list' and 'list'(即使)for 之间有空格)
  • 必须是[dic1.get(x, 0)+dic2.get(x, 0) for x in sorted(set(dic1.keys()) | set(dic2.keys()))]
  • 在python3中,[dic1.get(x, 0)+dic2.get(x, 0)for x in sorted(dic1.keys() | dic2.keys())]也应该可以工作(不需要set()
  • @ch3ka 我知道,在 Python 3.x 中,keys() 返回一个 view 对象,但在 Python 2.x 中返回一个 list。我指出这将在 2.7.x 中失败(为了清楚起见)。
  • @PraveenGollakota 正如你发布的那样,我在最后的笔记中添加了。 2.x 中的最佳选择是使用viewkeys()
猜你喜欢
  • 2021-11-02
  • 2010-10-06
  • 2021-05-23
  • 2013-06-10
  • 2010-10-26
  • 2023-01-30
  • 2019-09-09
  • 2022-11-13
相关资源
最近更新 更多