【问题标题】:Is there more elegant method for filtering dicts in python [duplicate]是否有更优雅的方法来过滤 python 中的字典 [重复]
【发布时间】:2013-07-12 09:57:07
【问题描述】:

我想知道 是否可以比

更短地过滤字典
>>> a={1:'a',2:'b',3:'c',4:'d',5:'e'}
>>> filterlist=[1,3,5]
>>> b=dict((key,value) for key,value in a.iteritems() if key in filterlist)
>>> b
{1: 'a', 3: 'c', 5: 'e'}

过滤(排序)可能基于值或键

EDIT1 :正如下面提到的那样,它的过滤不排序

【问题讨论】:

  • “排序”?这里没有排序...
  • Python 字典没有固定顺序;您无法对字典中的键进行排序。您可以生成键和/或值的排序列表,但不能生成排序字典。
  • 从 python 2.7 开始,有一个collections.OrderedDict,它会记住第一次插入键的顺序。
  • 嗯,比你已有的那一行短吗? dict(i for i in a.items() if i[0] in filterlist)

标签: python sorting dictionary python-2.6


【解决方案1】:

我认为您的意思是过滤,而不是排序。这是使用字典理解按键过滤字典的更优雅的方式(IMO):

>>>a = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}
>>>filterlist = [1, 3, 5]
>>>b= {key: a[key] for key in filterlist}
>>>b
{1: 'a', 3: 'c', 5: 'e'}

【讨论】:

  • 谢谢米兰,但我在 2.6.x 中尝试过,它给了我语法错误
  • @Koetsuji 也许你应该在你的问题中使用 python-2.6 标签而不是 python-2.7 标签?
【解决方案2】:

使用 cmets 中提到的 OrderedDict

根据键排序:

b = OrderedDict(sorted([(key, value) for (key,value) in a.items()]))

按值排序:

b = OrderedDict(sorted([(value, key) for (key,value) in a.items()]))

【讨论】:

    猜你喜欢
    • 2021-06-09
    • 1970-01-01
    • 2020-01-08
    • 2021-03-07
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 2012-01-15
    • 2012-01-25
    相关资源
    最近更新 更多