【问题标题】:How to convert an OrderedDict into a regular dict in python3如何在 python3 中将 OrderedDict 转换为常规字典
【发布时间】:2013-12-08 15:00:28
【问题描述】:

我正在努力解决以下问题: 我想像这样转换OrderedDict

OrderedDict([('method', 'constant'), ('data', '1.225')])

到这样的常规字典中:

{'method': 'constant', 'data':1.225}

因为我必须将它作为字符串存储在数据库中。转换后顺序不再重要,所以无论如何我都可以保留有序功能。

感谢任何提示或解决方案,

【问题讨论】:

  • repr(dict(OrderedDict([('method', 'constant'), ('data', '1.225')])))?
  • 是的,这也有效。谢谢!

标签: python type-conversion ordereddictionary


【解决方案1】:
>>> from collections import OrderedDict
>>> OrderedDict([('method', 'constant'), ('data', '1.225')])
OrderedDict([('method', 'constant'), ('data', '1.225')])
>>> dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
{'data': '1.225', 'method': 'constant'}
>>>

但是,要将其存储在数据库中,最好将其转换为 JSON 或 Pickle 等格式。使用 Pickle,您甚至可以保持订单!

【讨论】:

  • 谢谢,也感谢使用泡菜的建议。我会使用 pickle,实际上我会在其他地方使用,但是有些限制要求使用转换为字符串的 dict。
  • 将ordereddict转换为dict松散顺序吗?
  • 是的,它确实失去了秩序。
  • 请注意,thos 不适用于嵌套的 OrderedDictionary 数据,@thiruvenkadam 应该是公认的答案。
【解决方案2】:

尽管这是一个老问题,但我想说,如果您在有序 dict 中有一个有序 dict,那么使用 dict 将无济于事。可以转换那些递归有序字典的最简单方法是

import json
from collections import OrderedDict
input_dict = OrderedDict([('method', 'constant'), ('recursive', OrderedDict([('m', 'c')]))])
output_dict = json.loads(json.dumps(input_dict))
print output_dict

【讨论】:

  • 脚本等的好动作,即我不关心这个一次性任务的性能,只是给我字典,这样我就可以很好地打印它们
【解决方案3】:

很容易将您的OrderedDict 转换为普通的Dict,如下所示:

dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))

如果您必须将它作为字符串存储在数据库中,那么使用 JSON 是一种不错的选择。这也很简单,你甚至不用担心转换成普通的dict

import json
d = OrderedDict([('method', 'constant'), ('data', '1.225')])
dString = json.dumps(d)

或者直接将数据转储到文件中:

with open('outFile.txt','w') as o:
    json.dump(d, o)

【讨论】:

    【解决方案4】:

    如果您正在寻找不使用 json 模块的递归版本:

    def ordereddict_to_dict(value):
        for k, v in value.items():
            if isinstance(v, dict):
                value[k] = ordereddict_to_dict(v)
        return dict(value)
    

    【讨论】:

    • 不处理数据中的列表。
    【解决方案5】:

    这似乎是最简单且适用于 python 3.7 的方法

    from collections import OrderedDict
    
    d = OrderedDict([('method', 'constant'), ('data', '1.225')])
    d2 = dict(d)  # Now a normal dict
    

    现在检查一下:

    >>> type(d2)
    <class 'dict'>
    >>> isinstance(d2, OrderedDict)
    False
    >>> isinstance(d2, dict)
    True
    

    注意:这也有效,并给出相同的结果 -

    >>> {**d}
    {'method': 'constant', 'data': '1.225'}
    >>> {**d} == d2
    True
    

    还有这个——

    >>> dict(d)
    {'method': 'constant', 'data': '1.225'}
    >>> dict(d) == {**d}
    True
    

    干杯

    【讨论】:

      【解决方案6】:

      您可以使用“dict_constructor”参数。

      xmltodict.parse(text, attr_prefix='',dict_constructor=dict)

      【讨论】:

      • XMLparse如何进入图片?
      【解决方案7】:

      处理嵌套字典和可迭代但不使用json 模块的版本。嵌套字典变为dict,嵌套迭代变为list,其他所有内容都原样返回(包括字典键和字符串/字节/字节数组)。

      def recursive_to_dict(obj):
          try:
              if hasattr(obj, "split"):    # is string-like
                  return obj
              elif hasattr(obj, "items"):  # is dict-like
                  return {k: recursive_to_dict(v) for k, v in obj.items()}
              else:                        # is iterable
                  return [recursive_to_dict(e) for e in obj]
          except TypeError:                # return everything else
              return obj
      

      【讨论】:

        【解决方案8】:

        方法很简单

        >>import json 
        >>from collection import OrderedDict
        
        >>json.dumps(dict(OrderedDict([('method', 'constant'), ('data', '1.225')])))
        

        【讨论】:

          猜你喜欢
          • 2020-08-24
          • 2014-07-20
          • 1970-01-01
          • 1970-01-01
          • 2015-10-24
          • 1970-01-01
          • 2019-10-22
          • 2020-09-28
          • 2020-12-28
          相关资源
          最近更新 更多