Python:字典列表,如果存在,则增加一个字典值,如果不增加一个新字典 [英] Python : List of dict, if exists increment a dict value, if not append a new dict

查看:967
本文介绍了Python:字典列表,如果存在,则增加一个字典值,如果不增加一个新字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做类似的事情.

list_of_urls = ['http://www.google.fr/', 'http://www.google.fr/', 
                'http://www.google.cn/', 'http://www.google.com/', 
                'http://www.google.fr/', 'http://www.google.fr/', 
                'http://www.google.fr/', 'http://www.google.com/', 
                'http://www.google.fr/', 'http://www.google.com/', 
                'http://www.google.cn/']

urls = [{'url': 'http://www.google.fr/', 'nbr': 1}]

for url in list_of_urls:
    if url in [f['url'] for f in urls]:
         urls[??]['nbr'] += 1
    else:
         urls.append({'url': url, 'nbr': 1})

我该怎么办?我不知道该选择元组进行编辑还是找出元组索引?

How can I do ? I don't know if I should take the tuple to edit it or figure out the tuple indices?

有帮助吗?

推荐答案

这是一种非常奇怪的组织方式.如果您将其存储在字典中,这很容易:

That is a very strange way to organize things. If you stored in a dictionary, this is easy:

# This example should work in any version of Python.
# urls_d will contain URL keys, with counts as values, like: {'http://www.google.fr/' : 1 }
urls_d = {}
for url in list_of_urls:
    if not url in urls_d:
        urls_d[url] = 1
    else:
        urls_d[url] += 1

此更新计数字典的代码是Python中常见的模式".常见的是,创建了一个特殊的数据结构defaultdict只是为了使其变得更加容易:

This code for updating a dictionary of counts is a common "pattern" in Python. It is so common that there is a special data structure, defaultdict, created just to make this even easier:

from collections import defaultdict  # available in Python 2.5 and newer

urls_d = defaultdict(int)
for url in list_of_urls:
    urls_d[url] += 1

如果使用键访问defaultdict,并且该键尚未在defaultdict中,则会自动为该键添加默认值. defaultdict接受传入的可呼叫对象,并调用它来获取默认值.在这种情况下,我们传入了类int;当Python调用int()时,它返回零值.因此,第一次引用URL时,它的计数将初始化为零,然后将其添加一个.

If you access the defaultdict using a key, and the key is not already in the defaultdict, the key is automatically added with a default value. The defaultdict takes the callable you passed in, and calls it to get the default value. In this case, we passed in class int; when Python calls int() it returns a zero value. So, the first time you reference a URL, its count is initialized to zero, and then you add one to the count.

但是充满计数的字典也是一种常见的模式,因此Python提供了一个现成的类:containers.Counter您只需通过调用该类并传入任何可迭代的类来创建一个Counter实例.它建立了一个字典,其中的键是可迭代的值,而值是键在可迭代中出现的次数的计数.上面的示例变为:

But a dictionary full of counts is also a common pattern, so Python provides a ready-to-use class: containers.Counter You just create a Counter instance by calling the class, passing in any iterable; it builds a dictionary where the keys are values from the iterable, and the values are counts of how many times the key appeared in the iterable. The above example then becomes:

from collections import Counter  # available in Python 2.7 and newer

urls_d = Counter(list_of_urls)

如果您确实需要按照显示的方式进行操作,则最简单,最快的方法是使用这三个示例中的任何一个,然后构建所需的示例.

If you really need to do it the way you showed, the easiest and fastest way would be to use any one of these three examples, and then build the one you need.

from collections import defaultdict  # available in Python 2.5 and newer

urls_d = defaultdict(int)
for url in list_of_urls:
    urls_d[url] += 1

urls = [{"url": key, "nbr": value} for key, value in urls_d.items()]

如果您使用的是Python 2.7或更高版本,则可以单行执行:

If you are using Python 2.7 or newer you can do it in a one-liner:

from collections import Counter

urls = [{"url": key, "nbr": value} for key, value in Counter(list_of_urls).items()]

这篇关于Python:字典列表,如果存在,则增加一个字典值,如果不增加一个新字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆