Aly Abdelaziz
Aly Abdelaziz

Reputation: 290

Replace Values in Dictionary

I am trying to replace the values in the lines dictionary by the values of the corresponding key in the points dictionary

lines = {'24': ('2', '10'), '25': ('17', '18')} #k,v => Line ID(Points) 
points = {'10': ('2.416067758476', '2.075872272548'), '17': ('2.454725131264', '5.000000000000'), '18': ('1.828299357105', '5.000000000000'), '2': ('3.541310767185', '2.774647545044')} #Point ID => (X,Y)

i = 1
while i in range(len(lines)):
    for k, v in lines.iteritems():
        for k1, v1 in points.iteritems():
            for n, new in enumerate(v):
                if k1 == new:
                    lines[k] = v1
i += 1

The expected output is:

lines = {'24': ('2.416067758476', '2.075872272548', '3.541310767185', '2.774647545044'), '25': ('2.454725131264', '5.000000000000', '1.828299357105', '5.000000000000')}

The output from the above code

lines = {'24': ('3.541310767185', '2.774647545044'), '25': ('1.828299357105', '5.000000000000')}

If i create a list, then append that into the lines[k] i end up getting the all the values in the points list as that of each key element of lines. I think it is not looping out of the for loop properly.

Upvotes: 2

Views: 109

Answers (2)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95908

Just use a dictionary comprehension:

>>> {k:points[v[0]]+points[v[1]] for k,v in lines.items()}
{'24': ('3.541310767185', '2.774647545044', '2.416067758476', '2.075872272548'), '25': ('2.454725131264', '5.000000000000', '1.828299357105', '5.000000000000')}

Upvotes: 3

algrebe
algrebe

Reputation: 1651

You are getting the wrong output because of lines[k] = v . That is overwriting your previous assignment.

For your desired output -

lines = {'24': ('2', '10'), '25': ('17', '18')} #k,v => Line ID(Points)
points = {'10': ('2.416067758476', '2.075872272548'), '17': ('2.454725131264', '5.000000000000'), '18': ('1.828299357105', '5.000000000000'), '2': ('3.541310767185', '2.774647545044')} #Point ID => (X,Y)

new_lines = {}
for k, v in lines.iteritems():
    x, y = v
    new_v = []
    new_v.extend(points[x])
    new_v.extend(points[y])
    new_lines[k] = tuple(new_v)

print new_lines

Upvotes: 2

Related Questions