user1008636
user1008636

Reputation: 3181

Converting a dict into a list

I have

{key1:value1, key2:value2, etc}

I want it to become:

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

How can i do it as pythonically as possible?

Thanks!

Upvotes: 4

Views: 256

Answers (7)

inspectorG4dget
inspectorG4dget

Reputation: 113935

This code should solve your problem:

myList = []
for tup in myDict.iteritems():
    myList.extend(tup)

>>> myList
[1, 1, 2, 2, 3, 3]

Upvotes: 2

dawg
dawg

Reputation: 103814

If speed matters, use extend to add the key, value pairs to an 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 to each key, value pair.

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])

Prints:

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

Upvotes: 0

Levon
Levon

Reputation: 143047

Another entry/answer:

import itertools

dict = {'one': 1, 'two': 2}

bl = [[k, v] for k, v in dict.items()]
list(itertools.chain(*bl))

yields

['two', 2, 'one', 1]

Upvotes: 1

nye17
nye17

Reputation: 13347

given a dict, this will combine all items to a tuple

sum(dict.items(),())

if you want a list rather than a tuple

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

for example

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

x is then

['We', 'Love', 'Your', 'Dict']

Upvotes: 6

Jon Clements
Jon Clements

Reputation: 142136

The most efficient (not necessarily most readable or Python is)

from itertools import chain

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

Apart from materialising the lists, everything is kept as iterators.

Upvotes: 2

Ry-
Ry-

Reputation: 224904

This should do the trick:

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

For example:

dict = {'one': 1, 'two': 2}

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

This will print:

['two', 2, 'one', 1]

Upvotes: 11

sean
sean

Reputation: 3985

>>> a = {"lol": 1 }
>>> l = []
>>> for k in a.keys():
...     l.append( k )
...     l.append( a[k] )
... 
>>> l
['lol', 1]

Upvotes: 0

Related Questions