Reputation: 35
I have a list, a, defined as the following:
a = ['3', 'A', '+', 'Q', '2', '/', '*']
I have a dictionary, d, defined as the following:
d = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6' : 6, '7': 7, '8': 8, '9': 9, '0': 10, 'J': 11, 'Q': 12, 'K': 13}
I want to apply the dictionary to the elements of the list that are in the dictionary, including 3, A, Q, and 2, while leaving the operations in the same locations and in the same string format. I've tried to use list comprehension, but that tried to apply it to the operations as well.
My desired output would be as follows:
a = [3, 1, '+', 12, 2, '/', '*']
Any help would be appreciated.
Upvotes: 0
Views: 773
Reputation: 2418
The following program will do the substitution at the same time preserving any operators present in the mapping. However, you need to specify all the possible operators in another list,
a = ['3', 'A', '+', 'Q', '2', '/', '*']
ops = ['+','/','*','-'] # contains all operators
d = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6' : 6, '7': 7, '8': 8, '9': 9, '0': 10, 'J': 11, 'Q': 12, 'K': 13}
result = [c if c in ops else d.get(c, c) for c in a]
print(result)
The output is,
[3, 1, '+', 12, 2, '/', '*']
What if the dictionary contains mapping for '+'?,
a = ['3', 'A', '+', 'Q', '2', '/', '*']
ops = ['+','/','*','-'] # contains all operators
d = {'+':2,'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6' : 6, '7': 7, '8': 8, '9': 9, '0': 10, 'J': 11, 'Q': 12, 'K': 13}
result = [c if c in ops else d.get(c, c) for c in a]
print(result)
The output still is the same,
[3, 1, '+', 12, 2, '/', '*']
Upvotes: 0
Reputation: 2246
You can use dict.get
to specify default values if the key is not present in a dictionary:
a = ['3', 'A', '+', 'Q', '2', '/', '*']
d = {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6' : 6, '7': 7, '8': 8, '9': 9, '0': 10, 'J': 11, 'Q': 12, 'K': 13}
[d.get(c, c) for c in a] # produces [3, 1, '+', 12, 2, '/', '*']
This says, for each character c
in a
, lookup the value for that character in d
, or just return c
if the character is not present.
Upvotes: 5