字典中的python变量长度值

时间:2015-02-26 02:59:00

标签: python list python-2.7 dictionary

我有这样的字典:

d1 = {2: 'Joe', 5: 'Bob',  7: 'Doug', 9 : 'Bob', 10 : 'Doug', 12 : 'Joe', 15 : 'Dave'}

我想用它来填充这样的不同词典:

 def MakeDict():
     d, myList = {}, []
     for num in range(np.max(d1.keys())+1):
         value = d1.get(num)
         if value != None and value not in myList:
             myList.append(value)
         d[num] = myList
     return d

我希望函数返回: 0:[],1:[],2:['Joe'],3:['Joe'],4:['Joe'],5:['Joe','Bob'],6:[' Joe':'Bob'],7:['Joe','Bob','Doug']等。

而是它返回这个: 0:['Joe','Bob','Doug'],1:['Joe','Bob','Doug'],2:['Joe','Bob','Doug'],3: ['Joe','Bob','Doug'] ......

我认为它没有按照我希望的方式工作,因为列表的len正在改变。有办法解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

你的基本问题是

mylst = []
d1[1] = mylst         # this is a reference, not a copy!
mylst.append('Joe')   # modify the object...
d1[1]                 # => ['Joe'] !

相反,你想要

mylst = []
d1[1] = mylst[:]      # make a copy
mylst.append('Joe')
d1[1]                 # => []     # what you expected

d1 = {2: '7', 5: '1',  7: '25', 9 : '1', 10 : '25', 12 : '1', 15 : '55'}

d2, lst, seen = {}, [], set([None])
for i in range(max(d1) + 1):
    val = d1.get(i)
    if val not in seen:
        seen.add(val)
        lst.append(val)
    d2[i] = lst[:]

给出了

{0: [],
 1: [],
 2: ['7'],
 3: ['7'],
 4: ['7'],
 5: ['7', '1'],
 6: ['7', '1'],
 7: ['7', '1', '25'],
 8: ['7', '1', '25'],
 9: ['7', '1', '25'],
 10: ['7', '1', '25'],
 11: ['7', '1', '25'],
 12: ['7', '1', '25'],
 13: ['7', '1', '25'],
 14: ['7', '1', '25'],
 15: ['7', '1', '25', '55']}

答案 1 :(得分:1)

d1 = {2: '7', 5: '1',  7: '25', 9 : '1', 10 : '25', 12 : '1', 15 : '55'}
d2 = {}
prev = []
for i in range(max(d1.keys())+1):
    if i in d1:
        d2.setdefault(i, [x for x in prev]).append(d1[i])
    else:
        d2[i] = prev
    prev = d2[i]
print(d2)