4

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!

user1008636
  • 2,989
  • 11
  • 31
  • 45

7 Answers7

11

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]
erickrf
  • 2,069
  • 5
  • 21
  • 44
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • How exactly does this translate? I'm having trouble understanding it. – vergenzt Jul 05 '12 at 20:16
  • wow, didn't know that you can write comprehensions in that weird order +1 – unkulunkulu Jul 05 '12 at 20:16
  • 1
    @vergenzt: To be honest, I had no idea that you could flatten lists like that either, but you can :D And as for understanding it, you have to read it in reverse order because that's just how `for in` associates. – Ry- Jul 05 '12 at 20:17
  • @unkulunkulu it is actually a nested list comprehension – erickrf Jul 05 '12 at 20:18
  • What if I need to filter out certain keys when creating the list ? – user1008636 Jul 05 '12 at 20:18
  • 2
    @user1008636 Just like usual comprehensions: `[y for x in dict.items() for y in x if x[0] not in filtered_out]` – erickrf Jul 05 '12 at 20:20
  • @user1008636: Filter them out beforehand. (Edit: Yeah, what erickrf said `:)`) – Ry- Jul 05 '12 at 20:20
  • @erickrf, not really, if you look at it as a nested comprehension, he uses `x` in the outer comprehension while it's being introduced in the inner. – unkulunkulu Jul 05 '12 at 20:22
  • I think this is often called the [Martelli Method ;-)](http://stackoverflow.com/a/952952/298607) – dawg Jul 05 '12 at 20:32
6

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']
nye17
  • 12,857
  • 11
  • 58
  • 68
  • I would vote for this, but I've run out of votes, hence this comment. Great solution! – Ry- Jul 05 '12 at 20:28
2

This code should solve your problem:

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

>>> myList
[1, 1, 2, 2, 3, 3]
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
2

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.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
1

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]
Levon
  • 138,105
  • 33
  • 200
  • 191
0
>>> a = {"lol": 1 }
>>> l = []
>>> for k in a.keys():
...     l.append( k )
...     l.append( a[k] )
... 
>>> l
['lol', 1]
sean
  • 3,955
  • 21
  • 28
0

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%     --
dawg
  • 98,345
  • 23
  • 131
  • 206