简体   繁体   中英

Python Multiple Values For One Key in a defaultdict(dict)

I'm trying to create a directed graph with optional edge weights using a defaultdict. Here is my program:

import sys
import collections
myGraphLines = sys.stdin.readlines()
myGraphLines = [i.split() for i in myGraphLines]
myDefaultDict = collections.defaultdict(dict)
print(myDefaultDict)
myDefaultDict = {e[0] : {e[1] : e[2] if len(e) == 3 else True} for e in myGraphLines}
print(myDefaultDict)

When I run:

SanFrancisco Houston 1000
Austin           Houston 500
NYC   LA  3000
LA SanFrancisco
LA Ames 300
LA Detroit 200
^D
defaultdict(<class 'dict'>, {})
{'NYC': {'LA': '3000'}, 'LA': {'Detroit': '200'}, 'SanFrancisco': {'Houston': '1000'}, 'Austin': {'Houston': '500'}}

But if I am creating a directed graph, I need to have 'LA' pointing to 'SanFrancisco', 'Ames', and 'Detroit' But it is only pointing to Detroit.

I feel like I'm not using the defaultdict at all, but I can't find anywhere that talks about how to fill it up the way I want to. Thanks for any help.

When you use a defaultdict, you pretty much always have to populate it with an explicit loop:

myDefaultDict = collections.defaultdict(dict)
for e in myGraphLines:
    myDefaultDict[e[0]][e[1]] = e[2] if len(e) == 3 else True

It's the kind of thing where it initially feels like there should be some spiffy way to use some sort of dict comprehension or something. Even when you can use a comprehension, though, it's usually either quadratic time or a case where you don't really need a defaultdict at all.

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