Reputation: 75
I am fairly new at programming and I'm trying to practice making lists and dictionaries. I have a list that contains numbers and letters separated by a colon
lst = ['1:A', '2:B', '3:C', '4:A']
and I want to make a dictionary that looks like this
dictionary = {'1':'A', '2':'B', '3':'B', '4':'A'}
so that the key matches the number and the value matches the letter. I thought I could just make a nested list or something but I just couldn't get it to work. What is the best way to turn this type of list into a dictionary as stated?
Upvotes: 1
Views: 59
Reputation: 1121972
Use the dict()
constructor with a generator expression:
dict(v.split(':') for v in lst)
This works because dict()
accepts a sequence of (key, value) pairs as input; each str.split()
call produces these from the elements in your list.
Demo:
>>> lst = ['1:A', '2:B', '3:C', '4:A']
>>> dict(v.split(':') for v in lst)
{'1': 'A', '3': 'C', '2': 'B', '4': 'A'}
Upvotes: 5