替换字典中的值

时间:2016-09-20 19:37:42

标签: python python-2.7 dictionary

我正在尝试用values

中的lines dictionary替换values of the corresponding key中的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

预期输出为:

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

以上代码的输出

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

如果我创建一个列表,然后将其附加到lines[k] i中,最终得到点列表中的所有值都是行的每个关键元素的值。我认为它没有正确地循环出for循环。

2 个答案:

答案 0 :(得分:3)

只需使用词典理解:

>>> {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')}

答案 1 :(得分:2)

由于你的输出错误 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Scratch { public class Class1 { public Class1() { } public string TruncateOld(string value, int length) { string result = value; if (value != null) // Skip empty string check for elucidation { result = value.Substring(0, Math.Min(value.Length, length)); } return result; } public string Truncate(string value, int length) { return value?.Substring(0, Math.Min(value.Length, length)); } } } 。这会覆盖你之前的任务。

为您所需的输出 -

lines[k] = v