简体   繁体   English

有没有办法将字典列表转换为一组字典?

[英]Is there a way to convert a list of dicts to a set of dicts?

I'd like to convert a list of dicts into a set of dicts.我想将一个字典列表转换为一组字典。

For example:例如:

I have the following list:我有以下列表:

my_list = [{k1:v1, k2:v2}, {k3:v3, k4:v4}]

I simply want to convert it easily to a set of these dicts.我只是想轻松地将其转换为一组这些字典。

As long as my lists were holding simple data like Strings, there was no problem with:只要我的列表包含像字符串这样的简单数据,就没有问题:

new_list = set(myList)

But if they hold dicts, they fall on但是,如果他们持有 dicts,他们就会落在

TypeError: unhashable type: 'dict'

I'd rather not iterating the list and add each item to the set.我宁愿不迭代列表并将每个项目添加到集合中。 I'd rather have a straight forward method which will also support list of strings for example.我宁愿有一个直接的方法,它也将支持例如字符串列表。

Is that possible?那可能吗?

As the error suggests elements in a set must be hashable, which means that the must have a unique id (given by the hash method ).由于错误表明集合中的元素必须是可散列的,这意味着必须具有唯一的 id(由hash 方法给出)。 You could create your own dict extension class that gives the dict a hash, eg the hash of all its keys.你可以创建你自己的字典扩展 class 给字典一个 hash,例如它的所有键的 hash。 Or test/filter your list before converting it to a set.或者在将其转换为集合之前测试/过滤您的列表。 In short, a set cannot contain dicts.简而言之,集合不能包含字典。

Python doesn't have a builtin 'frozendict' type. Python 没有内置的“frozendict”类型。 If you really want to emulate what a frozendict would do, then you might want to to store a hashable equivalent of a dict.如果您真的想模拟 freezeddict 会做什么,那么您可能想要存储一个 dict 的可散列等效项。 For example:例如:

my_list = [{k1:v1, k2:v2}, {k3:v3, k4:v4}]

my_set = set(frozenset(d.items()) for d in my_lst)

If you want to get your dicts back all you need to do is:如果你想找回你的听写,你需要做的就是:

my_list = list(map(dict, my_set))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM