简体   繁体   English

Python中的一个键的多个值(dict)

[英]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. 我正在尝试使用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. 但如果我要制作有向图,我需要让'LA'指向'SanFrancisco', 'Ames','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. 我觉得我根本就没有使用defaultdict,但我找不到任何谈论如何以我想要的方式填充它的地方。 Thanks for any help. 谢谢你的帮助。

When you use a defaultdict, you pretty much always have to populate it with an explicit loop: 当您使用defaultdict时,您几乎总是需要使用显式循环填充它:

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. 即使你可以使用理解,它通常是二次时或者你根本不需要默认的情况。

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

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