user1220022
user1220022

Reputation: 12095

python map dictionary to array

I have a list of data of the form:

[line1,a]
[line2,c]
[line3,b]

I want to use a mapping of a=5, c=15, b=10:

[line1,5]
[line2,15]
[line3,10]

I am trying to use this code, which I know is incorrect, can someone guide me on how to best achieve this:

mapping = {"a": 5, "b": 10, "c": 15}
applyMap = [line[1] = 'a' for line in data]

Thanks

EDIT: Just to clarify here, for one line, however I want this mapping to occur to all lines in the file:

Input: ["line1","a"]

Output: ["line1",5]

Upvotes: 1

Views: 6741

Answers (4)

liupeixin
liupeixin

Reputation: 738

lineMap = {'line1': 'a', 'line2': 'b', 'line3': 'c'}  
cha2num = {'a': 5, 'b': 10, 'c': 15}  
result = [[key,cha2num[lineMap[key]]] for key in lineMap]  
print result  

what you need is a map to relevance 'a' -> 5

Upvotes: 0

Cédric Julien
Cédric Julien

Reputation: 80811

You could try with a list comprehension.

lines = [
   ["line1", "much_more_items1", "a"],
   ["line2", "much_more_items2", "c"],
   ["line3", "much_more_items3", "b"],
]
mapping = {"a": 5, "b": 10, "c": 15}
# here I assume the key you need to remove is at last position of your items
result = [ line[0:-1] + [mapping[line[-1]] for line in lines ]

Upvotes: 3

Reto Aebersold
Reto Aebersold

Reputation: 16644

Try something like this:

data = [
    ['line1', 'a'],
    ['line2', 'c'],
    ['line3', 'b'],
]

mapping = {"a": 5, "b": 10, "c": 15}

applyMap = [[line[0], mapping[line[1]]] for line in data]

print applyMap

Upvotes: 1

Dogbert
Dogbert

Reputation: 222358

>>> data = [["line1", "a"], ["line2", "b"], ["line3", "c"]]
>>> mapping = { "a": 5, "b": 10, "c": 15}
>>> [[line[0], mapping[line[1]]] for line in data]
[['line1', 5], ['line2', 10], ['line3', 15]]

Upvotes: 0

Related Questions