Python中的嵌套字典。如何不覆盖现有项目?

2024-10-05 13:21:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python把数据保存在字典里。有不同的点(x,y),每个点有不同的数据。你知道吗

import pprint
d=dict()

start = ((1, 3), "<Direction.NORTH: 0>")
target = ((0, 3), "<Direction.WEST: 270>")
weight = 666

startt = ((1, 3), "<Direction.WEST: 270>")
targett = ((0, 3), "<Direction.WEST: 270>")
weightt = 777

starttt = ((2, 3), "<Direction.NORTH: 0>")
targettt = ((0, 3), "<Direction.WEST: 270>")
weighttt = 888


d[start[0]] = {start[1]:(target, weight)}
d[startt[0]] = {startt[1]: (targett, weightt)}
d[starttt[0]] = {starttt[1]:(targettt, weighttt)}

pp = pprint.PrettyPrinter()
pp.pprint(d)

Python用第二个点覆盖第一个点,因为该点已经存在于dict中。如何实现Python在dict中比较dict的键? 输出:

    {(1, 3): {'<Direction.NORTH: 0>': (((0, 3), '<Direction.WEST: 270>'), 777)},
     (2, 3): {'<Direction.NORTH: 0>': (((0, 3), '<Direction.WEST: 270>'), 888)}} 

输出应该是这样的:

{ 
                                    (0, 3): {
                                                Direction.NORTH: ((0, 3), Direction.WEST, 1), 
                                                Direction.EAST: ((1, 3), Direction.WEST, 2) 
                                            },
                                    (1, 3): {
                                                Direction.WEST: ((0, 3), Direction.EAST, 2), 
                                                ... 
                                            }, 

Tags: 数据targetstartdictpprintwestweightnorth

热门问题