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
  • 46,825
  • 13
  • 96
  • 126
user3675188
  • 7,271
  • 11
  • 40
  • 76

4 Answers4

6
fixed_list = [x.items() for x in list]
keys,values = zip(*fixed_list)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
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,561
  • 5
  • 70
  • 76
Daniel
  • 5,095
  • 5
  • 35
  • 48
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,468
  • 3
  • 24
  • 45
  • 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,945
  • 3
  • 20
  • 45
  • 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