如何加入用for循环创建的词典?

时间:2015-07-15 09:45:49

标签: python list loops dictionary iteration

我是Python的新手。

我创建了一个代码,可以让我找到列表中给定项目后面的项目百分比。

给出一个清单:

list1=["a", "b", "a", "c", "a", "b", "c", "d", "e", "a", "b", "d", "e", "a", "c"]

我想找到,每个人都说“a”,每个项目跟随的百分比。代码返回:

[(33, 'a'), (25, 'b'), (16, 'e'), (16, 'd'), (16, 'c')]
[(30, 'a'), (20, 'e'), (20, 'd'), (20, 'c'), (20, 'b')]
[(25, 'e'), (25, 'd'), (25, 'b'), (25, 'a'), (12, 'c')]
[(33, 'e'), (33, 'd'), (33, 'b'), (33, 'a')]
[]  

输出是对的,这就是我想要的。
但我还想总结不同词典的每一个关键词,所以我可以得到类似的东西:

[(121, 'a'), (103, 'b'), (94, 'e'), (94, 'd'), (48, 'c')]

我没有办法做到这一点。我知道有一些方法可以对不同字典中每个键的值进行求和,但问题是字典是在for循环中创建的,因为我需要尽可能多的目标项目(在本例中为“a”)

我尝试用

迭代每个字典
   for key, value in dictio.items():
        dictio[key]=value + dictio.get(key, 0)
        print (dictio)

但结果很糟糕,而且与我想要的情况相差甚远。

我想告诉您是否可以加入多个词典,而不知道它们的编号(因为它们是在for循环中创建的)。

而且,由于我想了解更好的Python逻辑,我不想使用外部库,如果可能的话。

提前谢谢!

尼可罗马基

1 个答案:

答案 0 :(得分:6)

使用Counter

只是一种懒惰的方式
      ( SELECT  id AS ID, `recieved_datetime` `Date`, 'MT' AS Type, src_adress AS Msisdn,
               TEXT as text, CHAR_LENGTH(TEXT) AS QtyOfSymbols, 'OK' AS `Status`
            FROM  archiveincomingsms
            WHERE  1=1
              AND  recieved_datetime BETWEEN '2015-06-14 00:00:00'
                                         AND '2015-07-14 23:59:59'
      )
    UNION  ALL
      ( SELECT  id AS ID, `send_date` `Date`, 'MO' AS Type, scr_adress AS Msisdn,
                TEXT as text, CHAR_LENGTH(TEXT) AS QtyOfSymbols, 'OK' AS `Status`
            FROM  archiveoutgoingsms
            WHERE  1=1
              AND  send_date BETWEEN '2015-06-14 00:00:00'
                                 AND '2015-07-14 23:59:59'
      )
    ORDER BY  `Date` ASC
    LIMIT  0 ,100 

要排序

from collections import Counter
d = Counter()


mylist = [[(33, 'a'), (25, 'b'), (16, 'e'), (16, 'd'), (16, 'c')],
            [(30, 'a'), (20, 'e'), (20, 'd'), (20, 'c'), (20, 'b')],
            [(25, 'e'), (25, 'd'), (25, 'b'), (25, 'a'), (12, 'c')],
            [(33, 'e'), (33, 'd'), (33, 'b'), (33, 'a')],
            []]

for i in mylist:
    d.update(dict([(m,n) for n,m in i]))
>>>[(j,i) for i,j in d.items()]
[(121, 'a'), (48, 'c'), (103, 'b'), (94, 'e'), (94, 'd')]

获得百分比(假设)

>>>sorted([(j,i) for i,j in d.items()], key=lambda x:x[1])
[(121, 'a'), (103, 'b'), (48, 'c'), (94, 'd'), (94, 'e')]