简体   繁体   English

从python字典中选择性打印值

[英]Selectively printing values from a python dictionary

I have have a huge graph consisting of well over 100000 keys so efficiency is a huge issue. 我有一个巨大的图形,其中包含超过100000个键,因此效率是一个巨大的问题。 I am going through every keys' value, and for every value, I want it to be a key in another dictionary, with the values being the remaining values... Eg.. 我正在检查每个键的值,对于每个值,我都希望它成为另一本词典中的键,而这些值就是剩余的值。

graph = {'foobar': ['1', '2', '3']}
result = {'1' : ['2', '3'], '2' : ['1', '3'], '3' : ['1', '2']}  #in no particular order

Here is my code at the moment... 这是我目前的代码...

for i in heroDict.values():
    for j in i:
        if graph.has_key(j):
            tempDict = copy.deepcopy(i)
            tempDict.remove(j)
            heroList = tempDict
            graph[j] += heroList
        else:
            tempDict = copy.deepcopy(i)
            tempDict.remove(j)
            heroList = tempDict
            graph[j] = heroList
return graph

'heroDict' is a dictionary similar to the example except very very large. “ heroDict”是与示例类似的字典,但非常大。

The problem I am having is that my code is running very slowly because of the deepcopy() I am performing. 我遇到的问题是由于我执行的deepcopy(),我的代码运行非常缓慢。 so for the foobar example for example, I get '1' as a key. 因此对于foobar示例,我将“ 1”作为键。 I copy ['1', '2', '3'] into a temporary dict so the changes to it wont affect my final dictionary that i return. 我将['1','2','3']复制到临时字典中,因此对它的更改不会影响我返回的最终字典。 Then I remove the key from the ['1', '2', '3'] and assign the key '1' to it. 然后,从['1','2','3']中删除密钥,并为其分配密钥'1'。 So I'm left with {'1' : ['2', '3']} which is what I want but its taking too long because its iterating 100000+ times. 所以我剩下的是{'1':['2','3']},这是我想要的,但是它花了太长时间,因为它要迭代100000多次。

My final question is, can I improve this in any way so it runs faster? 我的最后一个问题是,我可以以任何方式进行改进以使其运行更快吗?

Any help is greatly appreciated. 任何帮助是极大的赞赏。

Permutations is included in itertools . 排列包含在itertools

A typical use in your example is : 您的示例中的典型用法是:

>>> from itertools import permutations
>>> values = graph['foobar']
>>> result = {x[0]:x[1:] for x in permutations(values)}
>>> print result
{'1': ('3', '2'), '2': ('3', '1'), '3': ('2', '1')}

Works with any number of values in foobar. 可在foobar中使用任意数量的值。 Permutations is a generator, so you may call one item at a time instead of generating the whole dict at once. 排列是一种生成器,因此您可以一次调用一个项目,而不是一次生成整个字典。

Not sure how fast that would be, though. 但是,不知道那将有多快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM