在循环中将字典附加到另一个字典

时间:2014-05-24 06:20:28

标签: python dictionary

我写了这段代码,我需要一些帮助来调试它。我不得不说我在这个网站上已经阅读过这方面的一些类似主题,但它无法帮助我调试我的代码:)

输出:

Number of max devices per route: 4
Number of routes: 2
Level of mobility: 2
routes  at T 0 : {0: [28, 14, 7, 4], 1: [22, 0]}
routes  at T 1 : {0: [29, 20, 28], 1: [28]}
{0: {0: [29, 20, 28], 1: [28]}, 1: {0: [29, 20, 28], 1: [28]}}

我的问题是我希望输出如下:

{ 0:{0: [28, 14, 7, 4], 1: [22, 0]} , 1: {0: [29, 20, 28], 1: [28]},}

但是,我不知道为什么最后一本字典会在新字典中重复出现。我试图调试它,但我无法成功。那么,如何在循环中将字典附加到另一个字典呢?

class myClassName(object):
    def __init__(self):
        """
        Class constructor.
        """

        self.no_devices = input("Number of max devices per route: ")
        self.no_routes = input("Number of routes: ")
        self.mob=input("Level of mobility: ")
        self.all_routes={}
        self.routes = {}

        self.arr = [0,1,2,3,4,5,6,7,8,9,10...,29] 

        for j in xrange(self.mob):
            for i in range(self.no_routes):
                random.shuffle(self.arr)                                          
                self.routes[i] = list(self.arr[0: random.randint(1,self.no_devices)])          
                self.all_routes[j]=self.routes


            print "routes  at T" ,j, ":" ,self.routes


        print self.all_routes

2 个答案:

答案 0 :(得分:0)

你可以这样做:     orig_dict.update(new_dict)

注意:如果两个词典都有一些相似的键,则会从new_dict

中选择值

编辑:

我认为您可能遇到的问题是因为您使用dict覆盖listroutes& all_routes

答案 1 :(得分:0)

由于@shaktimaan在循环的每次迭代中表示self.routes被覆盖,self.all_routes仅保留对self.routes的引用。我修改了代码,一次使它与python 3.4一起工作(即我有python的版本,对不起,我现在不用2.x)并且还修复了覆盖问题。

import random

class myClassName(object):
    def __init__(self):
        """
        Class constructor.
        """

        self.no_devices = int(input("Number of max devices per route: "))
        self.no_routes = int(input("Number of routes: "))
        self.mob = int(input("Level of mobility: "))
        self.all_routes={}


        self.arr = list(range(0,30))

        for j in range(self.mob):
            routes = {}
            for i in range(self.no_routes):
                random.shuffle(self.arr)                                          
                routes[i] = list(self.arr[0: random.randint(1,self.no_devices)])          
                self.all_routes[j]=routes


            print("routes  at T" ,j, ":" ,routes)


        print(self.all_routes)



if __name__ == '__main__':
    myClassName()

示例输出:

Number of max devices per route: 4
Number of routes: 2
2Level of mobility: 
routes  at T 0 : {0: [0, 10], 1: [22, 14]}
routes  at T 1 : {0: [16], 1: [22, 3, 5, 17]}
{0: {0: [0, 10], 1: [22, 14]}, 1: {0: [16], 1: [22, 3, 5, 17]}}

希望这对你有用。