如何根据某些条件将词典列表拆分为单独的词典列表?

2024-09-30 05:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我正在尝试根据某些条件将字典列表拆分为单独的字典列表

我的列表是这样的:

[{'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”中的用户名,依此类推

谢谢你的帮助


Tags: ofthetoid元素列表字典username
2条回答

找到同样的东西效果最好,如果我们按它排序,那么所有相同的名字都是紧挨着的

但是,即使在排序之后,我们也不需要手动执行这些操作——已经有了相应的工具itertools.groupby documentationa nice explanation how it works

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)

result是以用户名为键的dict

如果您想要列表列表,请执行result = [],然后执行result.append(list(group))

更好的方法是创建一个字典,其中username作为键,value作为用户属性列表

op = defauldict(list)
for user_dic in list_of_userdictss:
    op[user_dic.pop('username')].append(user_dic)
op = OrderedDict(sorted(user_dic.items()))

相关问题 更多 >

    热门问题