词典列表中的词典集

时间:2018-08-07 02:20:22

标签: python dictionary set

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

说我有以下词典列表:

depart_date_input = input("Estimated departure date (YYYY/MM/DD): ")
depart_time_input = input("Estimated departure time (HH:MM AM/PM) : ")
miles = 600
mph = 60
travel_minutes = timedelta(minutes=(miles / mph * 60))

depart_date = datetime.strptime(depart_date_input, "%Y/%m/%d")
depart_time = datetime.strptime(depart_time_input, "%I:%M %p")

depart_info = datetime(depart_date.year, depart_date.month, depart_date.day, 
depart_time.hour, depart_time.minute)
arrival_datetime = depart_info + travel_minutes

print(depart_date)
print(depart_time)
print(depart_info)
print(arrival_datetime)

仅尝试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']}] 时出现错误。

set

我接受邮件/电子邮件的正文,因为这是我将其定义为唯一的内容,并创建所有电子邮件正文的列表,然后为{{1}做一个生成器}等。

set(rm_dict)

这成功地使我从set(tuple())中获得了唯一的正文,但我希望从原始列表中获得整个词典。

2 个答案:

答案 0 :(得分:1)

您的错误消息告诉您一些重要信息:字典或列表都不是可哈希的,因此不能用作set的成员。解决该问题的一种方法是使用url = "/abc/mode/1234aqwer/mode1?query" replace = "1234aqwer" replaceWith = "3456asdf" console.log(url.replace(replace, replaceWith)),它是数据中电子邮件正文的第0个元素。

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

str

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

>>> 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!']}]

答案 1 :(得分:0)

设置项必须是可哈希的,而字典则不能。您可以使用<script> function myFunction() { var x = document.getElementById("fname"); x.value = x.value.toUpperCase(); } </script> <input type="text" id="fname" onblur="myFunction()"> 序列化所有字典,然后使用pickle获得唯一项,最后将它们反序列化为字典:

set

这将输出:

import pickle
print(list(map(pickle.loads, set(map(pickle.dumps, rm_dict)))))
相关问题