【问题标题】:Remove elements from key in Python dictionary从 Python 字典中的键中删除元素
【发布时间】:2015-10-11 07:40:20
【问题描述】:

我有一个程序可以找到字典中包含最多项目的键。如何删除字典中的元素,使其仅打印出来

*更新: 我刚刚发现我的程序不正确。我试图找到包含最多项目的密钥,然后返回相应的密钥

目标:

'd'

bird = { 'a': ['Parrot'], 'b': ['Columbidae'], 'c': ['Hummingbird']}

bird['d'] = ['Finch']
bird['d'].append('Owl')
bird['d'].append('Penguin')

def func(a):
    stor =[]
    for itterate in a.items():
        stor.append(itterate)
    return max(stor)


print func(bird)

当前输出:

('d', ['Finch', '猫头鹰', '企鹅'])

【问题讨论】:

  • print func(bird)[0]?或return max(stor)?
  • 您的max() 函数将按字母顺序查找最高的键。你也可以在这里使用return max(a)
  • 我更新了我的问题。我刚刚发现我的程序不正确。我试图找到包含最多项目的密钥,然后返回相应的密钥。 @BhargavRao

标签: python dictionary key element


【解决方案1】:

keyslen() 的值排序会得到你想要的结果。

>>> bird = { 'a': ['Parrot'], 'b': ['Columbidae'], 'c': ['Hummingbird'], 'd': ['kiwi', 'Crow', 'Sparrow']}

>>> print sorted(bird.keys(), key = lambda x:len(bird[x]))[-1]
>>> d

您可以将这一行嵌入到您的函数中:

bird = { 'a': ['Parrot'], 'b': ['Columbidae'], 'c': ['Hummingbird']}

bird['d'] = ['Finch']
bird['d'].append('Owl')
bird['d'].append('Penguin')

def func(a):
    return sorted(bird.keys(), key = lambda x:len(bird[x]))[-1]

print func(bird)

或者正如 Padraic 建议的那样,使用 max 函数和 lambda 可以以最小的开销完成您的工作:

def func(a):
    return max(bird.keys(), key = lambda x:len(bird[x]))

【讨论】:

  • 我希望能够调用该函数,以便它可以返回包含最多项目的键。
  • 这是O(n log n) 并创建一个全新的列表只是为了获得一个元素
  • 更新,@PadraicCunningham
【解决方案2】:

排序肯定不是得到你需要的东西的方法,你想要值是最长列表的键,所以在dict.items上使用max,使用值的长度作为最大值的键,然后返回第一个元素:

def func(d):
    return max(d.iteritems(), key=lambda x: len(x[1]))[0]

输出:

In [4]: func(bird)
Out[4]: 'd'

您也可以在 lambda 中进行查找,但 items 可能是最快的:

def func(d):
    return max(d, key=lambda x: len(d[x]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 2023-03-21
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    相关资源
    最近更新 更多