user25976
user25976

Reputation: 1025

python dictionary--turn set of one-itemed list values into float value

I have simply beginner python question. I have a dictionary that with values composed of one-itemed lists. How can I remove these items from the set of lists to get just a float?

dict = {key1: set([1]), key2: set([3]), key3:set([4])}

desired result:

resultdict = {key1: 1, key2: 3, key3: 4}

I had succeeded to remove the dictionary from a lists like so, but the set throws me off:

for k mydict:
    mydict[k] = mydict[k][0]

Upvotes: 1

Views: 147

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You can also make each set a list and access by the index:

 {k:list(v)[0] for k,v in my_dict.iteritems()}

If you are going to throw away the old dict you can use .pop

{k:v.pop() for k,v in my_dict.iteritems()}

I am not sure if you actually want floats or you meant ints in your question but if you want floats just cast as a float:

{k: float(v.pop()) for k,v in my_dict.iteritems()}

Upvotes: 2

mgilson
mgilson

Reputation: 309821

Something like this should work:

resultdict = {k: next(iter(s)) for k, s in input_dict.items()}

which works because next(iter(s)) takes the "first" element in the set:

>>> s = set([1])
>>> next(iter(s))
1

Note that you wouldn't want to do this with sets that have multiple items -- You'd never know which element you'd get.


There are other ways too:

list(s)[0]
tuple(s)[0]

would work too, but I'm guessing they'd be less efficient (though you'd have to timeit to know).

Upvotes: 1

Related Questions