user3378649
user3378649

Reputation: 5354

Python- Convert dictionary to dictionary with list value

I wanna convert dictionary to dictionary with list value

I wanna convert :

 f= {24149423: 59, 22621293.0: 367562.0, 24144369.0: 405017.0, 22662739.0: 276484.0, 22470388.0: 410315.0, 22624054.0: 398444.0, 22614201.0: 380106.0, 22564857.0: 90756.0, 22619259.0: 382386.0, 22692381.0: 388392.0}

to dictionary with list value

b =  {90756.0: [22564857.0], 388392.0: [22692381.0], 367562.0: [22621293.0], 410315.0: [22470388.0], 398444.0: [22624054.0], 382386.0: [22619259.0], 405017.0: [24144369.0], 276484.0: [22662739.0], 59: [24149423], 380106.0: [22614201.0]}

I try to write it this way:

from collections import defaultdict 

b = defaultdict(list)

for key, value in sorted(f.iteritems()):
    b[value].append(key)

I used map as well.

b = map(lambda k, v: f.update({k: v}), keys, values)

But none of these work.

Upvotes: 0

Views: 129

Answers (3)

BWStearns
BWStearns

Reputation: 2706

f= {24149423: 59, 22621293.0: 367562.0, 24144369.0: 405017.0, 22662739.0: 276484.0, 22470388.0: 410315.0, 22624054.0: 398444.0, 22614201.0: 380106.0, 22564857.0: 90756.0, 22619259.0: 382386.0, 22692381.0: 388392.0}
new_f = {x:[f[x]] for x in f}

Using dict comprehension you can edit it pretty fast.

Upvotes: 0

Teja
Teja

Reputation: 141

for key in f.keys():
    f[key] = [f[key]]

Also Works ....

Upvotes: 3

shx2
shx2

Reputation: 64308

Use a dict comprehension, like this:

b = { v: [k] for k,v in f.items() }

[k] is a one-element list containing the key, v is the value, which now plays the rold of the key in the resulting dictionary.

Upvotes: 2

Related Questions