簡體   English   中英

如何根據某些條件將字典列表拆分為單獨的字典列表?

[英]How can I split a list of dictionaries in separate lists of dictionaries based on some condition?

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

我想將具有相同用戶名的所有列表元素拆分並分組到單獨的字典列表中。 列表的元素 - 所以每個字典 - 按用戶名排序。

有沒有辦法遍歷字典和 append 每個元素到一個列表,直到“項目 1”中的用戶名等於“項目 1 + 1”中的用戶名等等?

謝謝您的幫助!

更好的方法是創建一個字典,其中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()))

如果我們按它對列表進行排序,則找到相同的東西效果最好——然后所有相同的名稱都彼此相鄰。

但即使在排序之后,我們也不需要手動做這些事情——已經有工具可以做到這一點。 :) - 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)

result是一個以用戶名作為鍵的字典

如果您想要一個列表列表,請執行result = []然后result.append(list(group))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM