【问题标题】:Dictionary of a dictionary with duplicate keys具有重复键的字典的字典
【发布时间】:2013-11-21 03:36:03
【问题描述】:

我想使用 pyMongo 将以下数据结构插入 MongoDB。唯一的问题是我使用的 xml 数据具有我想要保留的重复键,以及“关键字”和“相关性”子字典键。

for entity in root.find('output'):
   oc_entities[entity.tag] = {'keyword' : entity.text,
  'relevance' : entity.get('relevance')}

以上内容正在根据需要进行工作和插入,购买我丢失了大部分重复的键值数据。我知道字典不允许重复键,但有点难倒替代!

提前致谢

【问题讨论】:

    标签: python python-2.7 dictionary pymongo


    【解决方案1】:

    如果有重复的键,您可以将值设为列表。这是解决此问题的一种非常常见的方法。

    for entity in root.find('output'):
       if oc_entities.get(entity.tag):
         if type(oc_entities.get(entity.tag)) == 'dict':
           oc_entities[entity.tag] = [oc_entities[entity.tag]]
         oc_entities[entity.tag].append({'keyword' : entity.text, 'relevance' : entity.get('relevance')})
       else:
         oc_entities[entity.tag] = {'keyword' : entity.text, 'relevance' : entity.get('relevance')}
    

    【讨论】:

    • 谢谢。所以我可以在列表中同时拥有键和值? (我是 Python 新手!)。
    • 这将是一个字典列表,正如我在上面展示的那样。唯一的事情是,如果你只有一个元素,它就是一个元素列表。你可以通过加入你的 if 语句来解决这个问题......我只是懒得去做。您基本上会在 else 语句中去掉 dict 周围的括号,然后检查 if 子句以查看元素的类型是否为列表...如果不是,则将其设为列表。 ..aw 搞砸了,我会做的。
    • 不错的一个。在显示代码之前发表评论!很好的解决方案,而且很有效。非常感谢!
    • 您可能可以进一步优化此代码,但这是一般概念。
    • 没问题!很高兴我能帮上忙。
    猜你喜欢
    • 2022-08-18
    • 2012-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多