python tuple to dict
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping
--
Chapters
00:00 Question
00:37 Accepted answer (Score 351)
00:49 Answer 2 (Score 91)
01:02 Answer 3 (Score 53)
01:17 Answer 4 (Score 16)
01:33 Thank you
--
Full question
https://stackoverflow.com/questions/3783...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary #tuples
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping
--
Chapters
00:00 Question
00:37 Accepted answer (Score 351)
00:49 Answer 2 (Score 91)
01:02 Answer 3 (Score 53)
01:17 Answer 4 (Score 16)
01:33 Thank you
--
Full question
https://stackoverflow.com/questions/3783...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #dictionary #tuples
#avk47
ACCEPTED ANSWER
Score 366
Try:
>>> t = ((1, 'a'),(2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}
ANSWER 2
Score 96
A slightly simpler method:
>>> t = ((1, 'a'),(2, 'b'))
>>> dict(map(reversed, t))
{'a': 1, 'b': 2}
ANSWER 3
Score 54
Even more concise if you are on python 2.7:
>>> t = ((1,'a'),(2,'b'))
>>> {y:x for x,y in t}
{'a':1, 'b':2}
ANSWER 4
Score 17
>>> dict([('hi','goodbye')])
{'hi': 'goodbye'}
Or:
>>> [ dict([i]) for i in (('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14), ('CSCO', 21.14)) ]
[{'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}, {'CSCO': 21.14}]