To convert a tuple to dictionary in Python, use the dict() method. A dictionary object can be constructed using a dict() function. The dict() function takes a tuple of tuples as an argument and returns the dictionary. Each tuple contains a key-value pair.
Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.
The OrderedDict is a subclass of dict object in Python. The only difference between OrderedDict and dict is that, in OrderedDict, it maintains the orders of keys as inserted. In the dict, the ordering may or may not be happen. The OrderedDict is a standard library class, which is located in the collections module.
>>> 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'}
>>>
However, to store it in a database it'd be much better to convert it to a format such as JSON or Pickle. With Pickle you even preserve the order!
Even though this is a year old question, I would like to say that using dict
will not help if you have an ordered dict within the ordered dict. The simplest way that could convert those recursive ordered dict will be
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
It is easy to convert your OrderedDict
to a regular Dict
like this:
dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
If you have to store it as a string in your database, using JSON is the way to go. That is also quite simple, and you don't even have to worry about converting to a regular dict
:
import json
d = OrderedDict([('method', 'constant'), ('data', '1.225')])
dString = json.dumps(d)
Or dump the data directly to a file:
with open('outFile.txt','w') as o:
json.dump(d, o)
If you are looking for a recursive version without using the json
module:
def ordereddict_to_dict(value):
for k, v in value.items():
if isinstance(v, dict):
value[k] = ordereddict_to_dict(v)
return dict(value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With