外部文件中的Python字典

时间:2016-03-22 13:26:40

标签: python arrays dictionary import external

我正在尝试用Python创建一个字典,但我不知道如何做两件事。

  1. 当我在字典中搜索关键字时,我希望它能找到包含关键字的每个单词,而不仅仅是寻找直接匹配。例如。搜索:Cat - 结果:Cat,Allocate。

  2. 我希望字典能够加载外部文件,因此我在加载字典后可以保存新的术语。

2 个答案:

答案 0 :(得分:1)

您可以使用以下方法:
为1.

print ("Welcome back to the dictionary");

dict = {"CAT": "A small four legged animal that likes to eat mice",
        "DOG": "A small four legged animal that likes to chase cats",
        "ALLOCATE": "to give something to someone as ​their ​share of a ​total ​amount, to use in a ​particular way",
        }

def Dictionary():
    x = input("\n\nEnter a word: \n>>>");
    x = x.upper();
    found = False
    for y in dict:
        if x in y:
            found = True
            print (x,":",dict[x])
            Dictionary()
            break
    if not found:
        y = input ("Unable to find word. Enter a new definition of your word: \n>>>");
        dict.update({x:y})
        Dictionary()
Dictionary()

For 2:您可以直接从json文件加载数据

import json
dict = {}
with open("test.json", "r") as config_file:
    dict = json.load(config_file)

其中test.json是您的文件,例如
test.json

{"CAT": "A small four legged animal that likes to eat mice",
        "DOG": "A small four legged animal that likes to chase cats",
        "ALLOCATE": "to give something to someone as ​their ​share of a ​total ​amount, to use in a ​particular way",
        }

答案 1 :(得分:0)

这应该让你在分配中匹配cat。

for key in dict.keys():
    if x in key:
        do some stuff