0
['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!

4
  • 2
    @wnnmaw Minimal understanding was removed long back from the off-topic list. Commented Apr 9, 2014 at 21:34
  • 1
    @devnull, I didn't flag as off-topic, but last I check question are still expected to show minimal effort. That, and answers can be a lot more helpful/instructive if they address broken code or build off of what OP has already done Commented Apr 9, 2014 at 21:38
  • @wnnmaw That was a pun. Commented Apr 10, 2014 at 3:18
  • @devnull, oh man, this is embarrassing... well played Commented Apr 10, 2014 at 11:59

1 Answer 1

3
>>> 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

Sign up to request clarification or add additional context in comments.

3 Comments

This answer is nearly identical to Martijn Pieters' But in hindsight, that's rather harsh, sorry :(
a) i didn't copy his, b) i think it's a lot clearer than using map. but no worries, thanks for the explanation
Agreed, stripping first is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.