我如何根据一些条件将一个字典列表分割成不同的字典列表?

0 人关注

我是python的新手,我试图根据一些条件将一个字典列表分割成不同的字典列表。

This is how my list looks like this:

[{'username': 'AnastasiadesCY',
  'created_at': '2020-12-02 18:58:16',
  'id': 1.33421029132062e+18,
  'language': 'en',
  'contenttype': 'text/plain',
  'content': 'Pleased to participate to the international conference in support of the Lebanese people. Cypriot citizens, together with the Government 🇨🇾, have provided significant quantities of material assistance, from the day of the explosion until today.\n\n#Lebanon 🇱🇧'},
 {'username': 'AnastasiadesCY',
  'created_at': '2020-11-19 18:13:06',
  'id': 1.32948788307022e+18,
  'language': 'en',
  'contenttype': 'text/plain',
  'content': '#Cyprus stand ready to support all efforts towards a coordinated approach of vaccination strategies across Europe, that will prove instrumental in our fight against the pandemic.\n\nUnited Against #COVID19 \n\n#EUCO'},...

我想把所有列表中具有相同用户名的元素分割成独立的字典列表并进行分组。列表中的元素--所以每个字典--是按用户名排序的。

有没有一种方法可以在字典上循环,并将每个元素追加到一个列表中,直到 "项目1 "中的用户名等于 "项目1+1 "中的用户名,如此循环?

谢谢你的帮助!

python
list
loops
dictionary
if-statement
Chiara Vargiu
Chiara Vargiu
发布于 2021-02-18
3 个回答
h4z3
h4z3
发布于 2022-11-29
0 人赞同

如果我们对列表进行排序,找到相同的东西效果最好--那么所有相同的名字都会挨在一起。

但即使在分类之后,我们也不需要手动做这样的事情--已经有了相关的工具。 :)- itertools.groupby 文档 一个很好的解释,它是如何工作的

from itertools import groupby
from operator import itemgetter
my_list.sort(key=itemgetter("username"))
result = {}
for username, group in groupby(my_list, key=itemgetter("username")):
   result[username] = list(group)

替换代码1】是一个以用户名为键的dict。

If you want a list-of-lists, do result = []和then result.append(list(group)) instead.

Conans
Conans
发布于 2022-11-29
0 人赞同

更好的办法是创建一个字典,以 username 为键,以用户属性列表为值。

op = defauldict(list)
for user_dic in list_of_userdictss:
    op[user_dic.pop('username')].append(user_dic)
op = OrderedDict(sorted(user_dic.items()))
    
h4z3
这不是有效的python代码 - <list> ...而且请不要覆盖内置的 list 。还有,你为什么要使用两个dict?
@h4z3 我只是用 <list> 作为对一些列表的引用。我没有在任何地方覆盖内置的列表。
brucewlee
brucewlee
发布于 2022-11-29
0 人赞同