3

I want to split dictionary into two lists. one list is for key, another list is for value.

And it should be ordered as original

Original list:

[{"car":45845},{"house": 123}]

Expected result:

list1 = ["car", "house"]

list2 = [45845, 123]
Moinuddin Quadri
  • 43,657
  • 11
  • 92
  • 117
user3675188
  • 6,871
  • 10
  • 33
  • 72

4 Answers4

6
fixed_list = [x.items() for x in list]
keys,values = zip(*fixed_list)
Joran Beasley
  • 103,130
  • 11
  • 146
  • 174
5
list1 = [k for item in [{"car":45845},{"house": 123}] for k,v in item.iteritems()]
list2 = [v for item in [{"car":45845},{"house": 123}] for k,v in item.iteritems()]

For Python 3 use dict.items() instead of dict.iteritems()

Abhijeet
  • 8,114
  • 5
  • 68
  • 74
Daniel
  • 4,647
  • 4
  • 32
  • 46
0
a =[{"car":45845},{"house": 123}]

list1 = [i.values()[0] for i in a] #iterate over values 
list2=  [i.keys()[0] for i in a]   #iterate over keys
marmeladze
  • 6,048
  • 3
  • 24
  • 42
  • Although the code is appreciated, it should always have an accompanying explanation. This doesn't have to be long but it is expected. – peterh Apr 29 '15 at 00:44
0
original = [{"car":45845},{"house": 123}]
a_dict = {}
for o in original:
    a_dict.update(o)
print a_dict
print a_dict.keys()
print a_dict.values()

Output:

{'car': 45845, 'house': 123}
['car', 'house']
[45845, 123]
Burger King
  • 2,845
  • 3
  • 18
  • 44
  • this will not give the expected output in the case of duplicate keys (which may or may not be a valid concern) it also loses the original ordering (since dicts are unordered) which OP specifically asked to preserve – Joran Beasley Apr 29 '15 at 02:38