使用旧密钥创建新的dict但使用子值

时间:2013-07-13 04:12:16

标签: python python-2.7 dictionary key key-value

我是编程新手所以非常感谢所有帮助: 给出一个样本字典

d = {0 : (1, 2, 3), 1 : (2, 3, 4), 2 : (5, 6, 7)}

是否可以使用原始密钥创建新字典,但键的值是值的子值? 即:

0: (1, 2, 3) ---> 0: (4, 5, 6, 7), 1: (5, 6, 7, val(2), val(3))...

所以我希望删除2,3,因为它们已经包含在0的原始值中,依此类推。 *此外,我希望替换仅用于 n 次数

据我所知,这类似于制作一个子句?

问题在于,不是像上面那样使用给定的字典,而是使用每个键的给定值,我必须在大字典上执行此操作,所以我正在使用

-edit -

  

G = {

     
    

0:(1,2,3)

         

1:(3,4,5)

         

2:(4,5,6)

         

3:(7,8,9)

         

...

         

150:(10,11,12)}

  

- 编辑结束 -

k = d.keys()
v = d.values()

for v in k:
    print v " is connected to ", d[v]," by 1 length"

这是一种稍微迂回的方式来显示键及其值

-edit -

所以我想创建一个新词典,其新值如下:

  

G_new = {

     
    

0 :((3,4,5),(4,5,6),(7,8,9))

         

1 :((7,8,9),(值4),(值5))

         

...}

  

然后只保留唯一值并删除键的旧值中包含的值,以便:

  

G_new_final = {

     
    

0:(4,5,6,7,8,9)

         

1:(7,8,9等)

         

...} #until key 150

  

既然我正在处理很多数字,我猜我需要某种函数或字典理解?

- 编辑结束 -

谢谢!

2 个答案:

答案 0 :(得分:1)

>>> from collections import defaultdict
>>> a = defaultdict(set)
>>> d = {0: (1, 2, 3), 1: (2, 3, 4), 2: (5, 6, 7)}

#all subvalues of the values of x, no duplicate and without any value of key x
>>> [a[x].update(d.get(y, [])) for x in d for y in d[x]]
>>> [a[x].difference_update(d[x]) for x in d]

#convert it dict of tuple values
>>> {x:tuple(a[x]) for x in a}
{0: (4, 5, 6, 7), 1: (5, 6, 7), 2: ()}
>>> 

答案 1 :(得分:1)

g = {0: (1,2,3),1: (3,4,5),2: (4,5,6),3: (7,8,9)}
g2 = dict()
for key in g.keys():
    old_vals=set(g[key])
    new_vals=[]
    for val in old_vals:
        try:
            new_vals.extend(g[val])
        except KeyError:
            pass
    new_vals = tuple(set(new_vals)-old_vals)
    g2[key]=new_vals

给出

>>> g2
{0: (4, 5, 6, 7, 8, 9), 1: (8, 9, 7), 2: (), 3: ()}

但我不知道这与我answered previously?

的显着不同

编辑:有趣的是,这种方法似乎比收藏品更快?

import time
import random

def makeg(n):
    g=dict()
    for i in xrange(n):
        g[i] = tuple([random.randint(0,n) for _ in xrange(3)])
    return g

g=makeg(100000)

def m(g):
    g2 = dict()
    for key in g.keys():
        old_vals=set(g[key])
        new_vals=[]
        for val in old_vals:
            try:
                new_vals.extend(g[val])
            except KeyError:
                pass
        new_vals = tuple(set(new_vals)-old_vals)
        g2[key]=new_vals
    return g2

s1 = time.time()
m(g)
e1 = time.time()

from collections import defaultdict

def h(g):
    a = defaultdict(set)
    [a[x].update(g.get(y, [])) for x in g for y in g[x]]
    [a[x].difference_update(g[x]) for x in g]
    g2={x:tuple(a[x]) for x in a}
    return g2

s2 = time.time()
h(g)
e2=time.time()

mt =(e1-s1)
ht=(e2-s2)
print mt,ht,mt/ht

给出

nero@ubuntu:~/so$ python so.py 
0.556298017502 0.850471019745 0.654105789129