0

I am new to python, and I am trying to split a list of dictionaries into separate lists of dictionaries based on some condition.

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'},...

I would like to split and group all list's elements that have the same username into separate lists of dictionaries. The elements of the list - so each dictionary - are ordered by username.

Is there a way to loop over the dictionaries and append each element to a list until username in "item 1" is equal to username in "item 1 + 1" and so on?

Thank you for your help!

mhhabib
  • 2,975
  • 1
  • 15
  • 29

3 Answers3

0

A better would be to create a dictionary with username as key and value as list of user attributes

op = defauldict(list)
for user_dic in list_of_userdictss:
    op[user_dic.pop('username')].append(user_dic)
op = OrderedDict(sorted(user_dic.items()))
Conans
  • 461
  • 1
  • 4
  • 14
  • That isn't valid python code - ``... And please don't overwrite builtin `list`. And why do you use two dicts? – h4z3 Feb 18 '21 at 10:48
  • @h4z3 I just used `` as a reference to some list. I didn't override builtin list in anywhere. – Conans Feb 18 '21 at 11:08
0

Finding the same thing works the best if we sort the list by it - then all the same names are next to each other.

But even after sorting, we don't need to do such things manually - there are already tools for that. :) - itertools.groupby documentation and a 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 is a dict with usernames as keys

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

h4z3
  • 5,265
  • 1
  • 15
  • 29
0

list of dict to separate lists

data = pd.DataFrame(your_list_of_dict)

username_list = data.username.values.tolist()
brucewlee
  • 31
  • 4