简体   繁体   中英

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. 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.

The problem I am having is that my code is running very slowly because of the deepcopy() I am performing. so for the foobar example for example, I get '1' as a key. I copy ['1', '2', '3'] into a temporary dict so the changes to it wont affect my final dictionary that i return. Then I remove the key from the ['1', '2', '3'] and assign the key '1' to it. So I'm left with {'1' : ['2', '3']} which is what I want but its taking too long because its iterating 100000+ times.

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 .

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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