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

时间:2021-02-18 10:29:57

标签: python list loops dictionary if-statement

我是 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”中的用户名,依此类推?

感谢您的帮助!

2 个答案:

答案 0 :(得分: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()))

答案 1 :(得分:0)

如果我们按列表对列表进行排序,那么找到相同的东西效果最好——然后所有相同的名称都彼此相邻。

但即使在排序之后,我们也不需要手动做这些事情——已经有工具可以做到这一点。 :) - itertools.groupby documentationa nice explanation how it works

import 'dart:js' as js;

js.context.callMethod('info', ['Hello!']);

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,然后执行 result = []