Reputation: 295
I have a list of values
that match with certain keys
from a dictionary I created earlier.
myDict = {1:'A',2:'B',3:'C'}
myList = ['A','A','A','B','B','A','C','C']
How can I create/convert myList
into something like:
myNewList = [1,1,1,2,2,1,3,3]
Could someone point me in the right direction?
Not sure if it matters, I created the dictionary using json in another script, and I am now loading the created dictionary in my current script.
Upvotes: 3
Views: 111
Reputation: 105
myDict = {1:'A',2:'B',3:'C'}
myList = ['A','A','A','B','B','A','C','C']
value = [key for i in myList for key, value in myDict.iteritems() if i == value]
print value
I recommend you read a bit about the compression list http://docs.python.org.ar/tutorial/3/datastructures.html
Upvotes: 1
Reputation: 46
This works too:
myNewList = []
for val in myList:
for key, value in myDict.iteritems():
if val == value:
myNewList.append(key)
Upvotes: 0
Reputation: 13984
One easy way is to just invert myDict
and then use that to map the new list:
myNewDict = {v: k for k, v in myDict.iteritems()}
myNewList = [myNewDict[x] for x in myList]
Also take a look at this for Python naming conventions: What is the naming convention in Python for variable and function names?
Upvotes: 8