创建“集合字典". [英] Creating a "dictionary of sets"

查看:47
本文介绍了创建“集合字典".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要有效地将数据存储在类似于集合字典"的内容中,例如有一个字典,该字典具有与每个唯一键匹配的多个(唯一)值.我的数据源将是(不是很好)结构化的XML.

I need to efficiently store data in something that would resemble a "dictionary of sets" e.g. have a dictionary with multiple (unique) values matching each unique key. The source of my data would be a (not very well) structured XML.

我的想法是:我将浏览一些元素并找到键.如果该键不存在,则将其添加到字典中;如果它已经存在,则只需在相应的键中添加一个新值.

My idea is: I will look through a number of elements and find keys. If the key does not exist, add it to dictionary, if it already exists, just add a new value in the corresponding key.

结果将是这样的:

{
 'key1': {'1484', '1487', 1488', ...}
 'key2': {'1485', '1486', '1489', ...}
 'key3': {'1490', '1491', '1492', ...}
 ...
}

我需要随时随地添加新密钥.我需要将唯一值推入每个集合.我需要能够遍历整个字典.

I need to add new keys on the go. I need to push unique values into each set. I need to be able to iterate through the whole dictionary.

我不确定这是否可行,但是如果有人可以向正确的方向推动我,我将不胜感激.

I am not sure if this is even feasible, but if anybody could push me in the right direction, I would be more than thankful.

推荐答案

我不会对此进行基准测试,但以我的经验,本机命令更快

I'm not going to benchmark this but in my experience native dicts are faster

store = {}
for key, value in yoursource:
    try:
        store[key].add(value)
    except KeyError:
        store[key] = {value}

这篇关于创建“集合字典".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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