Convert dict to list

I have

{key1:value1, key2:value2, etc} 

I want him to become:

 [key1,value1,key2,value2] , if certain keys match certain criteria. 

How can I do this as python as possible?

Thanks!

+4
source share
7 answers

This should do the trick:

 [y for x in dict.items() for y in x] 

For instance:

 dict = {'one': 1, 'two': 2} print([y for x in dict.items() for y in x]) 

This will print:

 ['two', 2, 'one', 1] 
+11
source

given a dict , this will merge all the elements into a tuple

 sum(dict.items(),()) 

if you need a list, not a tuple

 list(sum(dict.items(),())) 

eg

 dict = {"We": "Love", "Your" : "Dict"} x = list(sum(dict.items(),())) 

x then

 ['We', 'Love', 'Your', 'Dict'] 
+6
source

This code should solve your problem:

 myList = [] for tup in myDict.iteritems(): myList.extend(tup) >>> myList [1, 1, 2, 2, 3, 3] 
+2
source

Most effective (not necessarily readable or Python)

 from itertools import chain d = { 3: 2, 7: 9, 4: 5 } # etc... mylist = list(chain.from_iterable(d.iteritems())) 

Besides materializing lists, everything is stored as iterators.

+2
source

Another post / answer:

 import itertools dict = {'one': 1, 'two': 2} bl = [[k, v] for k, v in dict.items()] list(itertools.chain(*bl)) 

gives

 ['two', 2, 'one', 1] 
+1
source
 >>> a = {"lol": 1 } >>> l = [] >>> for k in a.keys(): ... l.append( k ) ... l.append( a[k] ) ... >>> l ['lol', 1] 
0
source

If speed matters, use the extension to add the key, value pairs to the empty list:

 l=[] for t in sorted(d.items()): return l.extend(t) >>> d={'key1':'val1','key2':'val2'} >>> l=[] >>> for t in sorted(d.items()): ... l.extend(t) ... >>> l ['key1', 'val1', 'key2', 'val2'] 

Not only faster, this form is easier to add logic for each key pair, values.

Speed ​​Comparison:

 d={'key1':'val1','key2':'val2'} def f1(): l=[] for t in d.items(): return l.extend(t) def f2(): return [y for x in d.items() for y in x] cmpthese.cmpthese([f1,f2]) 

Print

  rate/sec f2 f1 f2 908,348 -- -33.1% f1 1,358,105 49.5% -- 
0
source

All Articles