0

我有两本词典。我必须将第一个中的值与第二个中的键匹配,然后返回在第二个字典中找到的值。到目前为止,我想出了这个:

d1 = {}
with open ("file1.txt") as f:
   for line in f:
       (key,val) = line.split()
       d[int(key)] = val
d2 = {}
with open("file2.txt") as f:
   for line in f:
      (key,val) = line.split()
      d[int(key)] = val

for item in d1.values():
     if d2.has_key(item):
         print value.d2(item)

我不断收到错误“太多的值无法解包”,除此之外,我的脚本真的会做我想做的事吗?

更新(对不起,我不知道我可以编辑我的问题!):我的两个文本文件,file1 将单词映射到数字系统,file2 将数字映射到其相关类别。最终结果应该是 file1 的单词链接到它在 file2 中找到的类别。这是通过首先将单词链接到一个数字,然后将该数字链接到一个类别来完成的。例如:Aanbidden(荷兰语)> 12 > 猫。“影响”。我文件中的行如下所示:

文件 1.txt:

aanbidden: 12 13 14 57 58  
leven : 15
drinken: 23 56 
... 
(As you see each key can have one or more values)

文件2.txt:

12: affect
13: posemo
14: Posfeel
15: Optim
23: discrep
56: money
57: metaph
58: religious
...
(In this file each key has only one value)
4

1 回答 1

1

根据您的评论,以下似乎是您想要的:

d1 = {}
with open ("file1.txt") as f:
   for line in f:
       (key,val) = line[:-1].split(": ")
       d1[key] = val.split()

d2 = {}
with open("file2.txt") as f:
   for line in f:
      (key,val) = line[:-1].split(": ")
      d2[key] = val

for word, nums in d1.items():
    print word, "->",
    for num in nums:
        if d2.has_key(num):
            print d2[num],
    print

鉴于您在上面发布的文件,它会打印以下内容:

drinken -> discrep money
leven -> Optim
aanbidden -> affect posemo Posfeel metaph religious
于 2013-01-23T15:53:17.193 回答