词典列表中的词典集 [英] set of dictionaries in list of dictionarys

查看:73
本文介绍了词典列表中的词典集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图在列表中找到一组字典。

trying to find a set of dictionaries in a list.

说我有以下字典列表:

rm_dict = [{'name':'rick','subject':'adventure time mortttty buugh','body':['wubba lubba dub dubbb motha f*&^%!', 'morty get over here!']},
 {'name':'rick','subject':'adventure time mortttty buugh','body':['wubba lubba dub dubbb motha f*&^%!', 'morty get over here!']},
 {'name':'morty','subject':'re:adventure time mortttty buugh','body':['youre drunk rick!', 'I'm going to get mom', 'you always do this']}]

尝试只设置 ,我得到一个错误。

trying just set, I get an error.

set(rm_dict)

我接受邮件/电子邮件的正文,因为这就是我要的内容使用定义为唯一,并创建所有电子邮件正文的列表,然后为 set(tuple())等做一个生成器。 / p>

I take the body of the message/email, because that's what I'll use to define as unique, and create a list of the body of all of the emails, and then I will do a generator for set(tuple()) etc..

list_of_body = [x['body'] for x in rm_dict]
>>[['wubba lubba dub dubbb motha f*&^%!'],
  ['wubba lubba dub dubbb motha f*&^%!'],
  ['youre drunk rick!']]

[list(item) for item in set(tuple(row) for row in list_of_body)]
>>[['wubba lubba dub dubbb motha f*&^%!'], ['youre drunk rick!']]

这成功地使我从 list_of_body 中获得了唯一的正文,但是我希望从原始列表中获得 whole 词典。

This succeeds in getting me the unique bodies from the list_of_body, but I want the whole dictionary from the original list.

推荐答案

您的错误消息告诉您一些重要信息:字典或列表都不是可哈希的,因此不能用作set的成员。解决该问题的一种方法是使用 str ,它是数据中电子邮件正文的第0个元素。

Your error message is telling you something important: neither a dictionary or a list is hashable, and so cannot be used as a member of set. One way to work around that is to use the str that is the 0th element of the email body in your data.

您可以使用列表理解功能根据其键之一唯一化您的列表:

You can "uniqify" your list based on one of its keys with a list comprehension:

>>> seen = set()
>>> [i for i in rm_dict if i['body'][0] not in seen and not seen.add(i['body'][0])]
[{'name': 'rick',
  'subject': 'adventure time mortttty buugh',
  'body': ['wubba lubba dub dubbb motha f*&^%!']},
 {'name': 'morty',
  'subject': 're:adventure time mortttty buugh',
  'body': ['youre drunk rick!']}]

这里是另一种形式,没有理解:

Here's another form, without the comprehension:

>>> seen = set()
>>> emails = []
>>> for i in rm_dict:
...     body = i['body'][0]
...     if body not in seen:
...         emails.append(i)
...         seen.add(body)
...         

>>> emails
[{'name': 'rick',
  'subject': 'adventure time mortttty buugh',
  'body': ['wubba lubba dub dubbb motha f*&^%!']},
 {'name': 'morty',
  'subject': 're:adventure time mortttty buugh',
  'body': ['youre drunk rick!']}]

这篇关于词典列表中的词典集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆