从输入值设置多个字典值?

时间:2016-12-06 22:36:32

标签: python dictionary

我试图在输入值中设置python中的多个字典值,但总是返回错误通知。但如果我在脚本中声明字典,它将运行良好。所以我试过了:

adj=defaultdict(list)

iteration=input("the number of edges that constructed: ")
for i in range (0,int(iteration)):
    #A(vertices1)  B(vertices2) W(weight)
    abw=input("A B W : ")
    if len(abw)==1:
        a=int(abw)
        valueBW=(None)
        if a in adj:
            adj[a].append(())
        else:
            adj[a].append(())
            #dict.fromkeys(a,None)
    else:
        a,b,w=abw.split(' ')
        a=int(a)
        valueBW=(int(b),int(w))
        if a in adj:
            adj[a].append(valueBW)
        else:
            #adj.update({a : [(int(b),int(w))]})
            adj[a].append(valueBW)

这是输入示例:

the number of edges that constructed: 8
A B W : 0 1 4
A B W : 0 3 8
A B W : 1 4 1
A B W : 1 2 2
A B W : 4 2 3
A B W : 2 5 3
A B W : 3 4 2
A B W : 5

如果我在代码中声明它,这是字典:

adj = {
  0: [(1, 4),(3, 8)],
  1: [(4, 1),(2, 2)],
  4: [(2, 3)],
  2: [(5, 3)],
  3: [(4, 2)],
  5: [],
  }

我的代码是对的吗?

1 个答案:

答案 0 :(得分:0)

你的问题并不完全清楚你想要什么,但我相信这就是你所追求的:

# Always show your imports - we don't know if
# you got defaultdict from here or somewhere else
from collections import defaultdict

adj=defaultdict(list)

iteration=input("the number of edges that constructed: ")

# You can omit the start if it's zero.
# and if you're not using the variable,
# indicate that by using `_` as your name
for _ in range (int(iteration)):
    #A(vertices1)  B(vertices2) W(weight)
    abw=input("A B W : ")
    if len(abw)==1:
        a=int(abw)
        # Don't append anything
        # just access it so that
        # it exists.
        adj[a]
    else:
        # By default, `.split()` uses any whitespace.
        # This makes `1     2 3` work just fine.
        a,b,w=abw.split()
        a=int(a)
        valueBW=(int(b),int(w))
        adj[a].append(valueBW)

使用您提供的输入,这给了我:

{0: [(1, 4), (3, 8)],
 1: [(4, 1), (2, 2)],
 2: [(5, 3)],
 3: [(4, 2)],
 4: [(2, 3)],
 5: []}

这看起来像您的预期输出。请注意,字典不是有序的,所以为了让它显示如下所示:

import pprint

pprint.pprint(adj)