Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deconstructing and reconstructing python dictionary

I have a dictionary which I need to deconstruct its keys and values in perhaps two lists(or any other type that does the job) and later in another function, construct the exact same dictionary putting back the keys and values. What's the right way of approaching this?

like image 246
Yasin Avatar asked Apr 29 '16 09:04

Yasin


1 Answers

You can use dict.items() to get all the key-value pairs from the dictionary, then either store them directly...

>>> d = {"foo": 42, "bar": 23}
>>> items = list(d.items())
>>> dict(items)
{'bar': 23, 'foo': 42}

... or distribute them to two separate lists, using zip:

>>> keys, values = zip(*d.items())
>>> dict(zip(keys, values))
{'bar': 23, 'foo': 42}
like image 132
tobias_k Avatar answered Oct 14 '22 14:10

tobias_k