将词典列表转换为一组词典 [英] Convert a list of dictionaries into a set of dictionaries

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

问题描述

如何从一个词典列表中制作一组词典?

How can i make a set of dictionaries from one list of dictionaries?

示例:

import copy

v1 = {'k01': 'v01', 'k02': {'k03': 'v03', 'k04': {'k05': 'v05'}}}
v2 = {'k11': 'v11', 'k12': {'k13': 'v13', 'k14': {'k15': 'v15'}}}

data = []
N = 5
for i in range(N):
    data.append(copy.deepcopy(v1))
    data.append(copy.deepcopy(v2))

print data

如何从列表 data 创建一组字典?

How would you create a set of dictionaries from the list data?

NS:当一个字典在结构上相同时,它等于另一个.也就是说,他们完全具有相同的键和相同的值(递归)

NS: One dictionary is equal to another when they are structurally the same. That means, they got exactly the same keys and same values (recursively)

推荐答案

一种便宜的解决方法是序列化您的字典,例如:

A cheap workaround would be to serialize your dicts, for example:

import json

dset = set()

d1 = {'a':1, 'b':{'c':2}}
d2 = {'b':{'c':2}, 'a':1} # the same according to your definition
d3 = {'x': 42}

dset.add(json.dumps(d1, sort_keys=True))
dset.add(json.dumps(d2, sort_keys=True))
dset.add(json.dumps(d3, sort_keys=True))

for p in dset:
    print json.loads(p) 

从长远来看,将整个内容包装在诸如 SetOfDicts 之类的类中是很有意义的.

In the long run it would make sense to wrap the whole thing in a class like SetOfDicts.

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

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