Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 替换字典中的值_Python_Python 2.7_Dictionary - Fatal编程技术网

Python 替换字典中的值

Python 替换字典中的值,python,python-2.7,dictionary,Python,Python 2.7,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.5

我试图用
点词典中相应键的
值替换
行词典中的

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

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

由于以下原因,您得到了错误的输出
行[k]=v
。这将覆盖您以前的作业

对于您想要的输出-

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

只需使用字典即可:

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

谢谢投票赞成更全面。谢谢。我投了另一个票,因为它更全面。