python - 从 Python 字典中的 key 中删除元素

标签 python dictionary key element

我有一个过程可以找到字典中包含最多项目数的键。如何删除字典中的元素,以便它只打印出来

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

目标:

'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', 'Owl', 'Penguin'])

最佳答案

根据值的 len()进行排序将获得您想要的结果。

>>> 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]))

关于python - 从 Python 字典中的 key 中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33062668/

相关文章:

python - 如何减慢动画速度

c# - 如何使具有相同数据的对象具有相同的键?

java - Hazelcast 分布式执行器服务 KeyOwner

C++ 将 DWORD 值写入某个注册表项的所有子项

python - Python 中 timedelta 对象的百分比?

jquery - 将 django-dynamic-formset 与来自 d​​jango-extra-views 的 CreateWithInlinesView 一起使用 - 多个表单集

python - 作为单元测试一部分启动/停止守护进程的最佳实践(使用 pytest)

Python:查询字典到 JSON

Python unittest - 用列表断言字典

php - 将多个键分配给数组中的相同值