user3517147
user3517147

Reputation: 1

Converting list to dictionary in Python

['monaco:1\n', 'russia:2\n', 'denmark:3\n']

into a dictionary in Python 3.3.3, plus any ideas on how to remove the '\n'?

Thanks!

Upvotes: 0

Views: 91

Answers (1)

mhlester
mhlester

Reputation: 23231

>>> mylist = ['monaco:1\n', 'russia:2\n', 'denmark:3\n']
>>> dict(s.strip().split(':') for s in mylist)
{'denmark': '3', 'russia': '2', 'monaco': '1'}

s.strip().split(':') takes a string and outputs a list of before and after the colon, with whitespace removed from the ends

Upvotes: 3

Related Questions