【问题标题】:python- create 2-dimensional dictionary from the input filepython-从输入文件创建二维字典
【发布时间】:2015-03-01 04:02:47
【问题描述】:

我是 python 新手。我有一个这样的输入文件:

1 2 3 4 /a/
5 6 7 8 /b/
9 0 1 2 /c/
3 4 5 6 /d/

我需要读取文件并将数字存储在字典中,例如 d,但使用最后一列中的单词作为索引。比如我想

d['aa'] = 1, 
d['ab'] = 2, 
d['ac'] = 3 , 
d['ad'] = 4 
...

【问题讨论】:

  • 你能解释一下5678吗?
  • 当然!假设列的名称与行相同。因此, d['b']['a']=5 , d['b']['b']=6, d['b']['c']=7,d['b'] ['d']=8,d['c']['a' ]=9 以此类推。

标签: python arrays dictionary


【解决方案1】:

字典并不是这样工作的。字典基本上是一个哈希表。按键像一组一样工作;在那个重复的条目是不允许的。我认为您正在尝试做的是:

data = """1 2 3 4 /a/
5 6 7 8 /b/
9 0 1 2 /c/
3 4 5 6 /d/"""

result = {}
for line in data.split("\n"):
    *numbers, index = line.split(" ")
    index = index.replace("/", "")
    result[index] = numbers
print(result)

字典索引没有排序。如果您想保留他们的订单,您也可以随时存储:

indexes_ordered = []
...
indexes_ordered.append(index)

或查看this question 了解排序。

最后,要获取您的值,您可以遍历键:

for key in result:
    print(result[key])

或者,根据您的选择,将result 更改为indexes_ordered。您可以通过任何多种形式的列表理解对每个字典条目的有序列表进行处理。

对于奖励积分,您可以让字典条目指向其他字典条目:

x = {}
x[0] = 1
x[1] = 2
x[2] = 3
x[3] = "yay!"
result = 0
y = 0
while y in x: y = x[y]
result = y
print(result)

要获得您在编辑后的问题中描述的内容,您可以执行以下操作:

another_result = {}
a = ord('a')
for key in result:
    x = result[key]
    for n in range(len(x)):
        another_result[key + chr(a+n)] = x[n]
for key in another_result: print(key, another_result[key])

如果您有任何问题,请发表评论。

【讨论】:

  • 非常感谢您的建议!为从列和行中的单词串联获得的每个数字都有一个唯一索引怎么样?例如,我们用 d['ab'] 代替 d['a']['b'] 等等。
  • 我知道您在这方面投入了足够多的时间。但是您知道我该如何实现吗?
  • @ahb65 我附上了我的答案。
【解决方案2】:

解决方法如下:

d={};k=0;key=[];val=""
tFile=open("inputFile",'r')
dat=tFile.readlines()
for i in range(len(dat)):
    val += a[i].split('/')[0] # store all the numbers in val
    key.append(a[i].split('/')[1].strip()) # store letters in key
val = " ".join(val.split()) # remove extra white spaces
#merge keys and values into a single dictionary
for i in key:
    for j in key:
        d[i+j]=val.split(" ")[k].strip()
        k+=1
return d

【讨论】:

    猜你喜欢
    • 2014-11-13
    • 1970-01-01
    • 2014-04-19
    • 2012-11-07
    • 2018-03-29
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    相关资源
    最近更新 更多