Python 3接受用户输入以访问另一个文件中的字典

时间:2019-01-30 07:17:41

标签: python dictionary input

我想让用户输入(current_input)并使用它来访问名为(john.py)的文件中名为(john)的字典。如果用户输入john,我希望for语句检查john.john并打印出键(x)和属性(john.john [x])。有任何想法吗?

import john
current_fugitive = input("Please enter the name of the fugitive: ")
if current_fugitive =="john":
    for x in current_fugitive.current_fugitive:
        print(x, current_fugitive.current_fugitive[x])

(编辑) 有效的原始代码:

if current_fugitive =="john":
for x in john.john::
    print(x, john.john[x])

2 个答案:

答案 0 :(得分:2)

您不想这样做。这是初学者常犯的错误,在这些错误中,您将意义分配给变量名。不要这样做-您的具有含义,但是您的变量名应该是好的,描述性的名称,对于程序员来说是清楚的,但对程序毫无意义。

很可能john.py应该是john.json,而您应该这样做:

from pathlib import Path
import json

fugitives = {}

for fugitive_json in Path(__file__).glob("*.json"):
    # find all the *.json files that are sibling to the current file
    with fugitive_json.open() as f:
        new_fugitive = json.load(f)
        fugitives[fugitive_json.stem] = new_fugitive
        # Path("path/to/john.json").stem == "john"

user_input = input("Which fugitive? ")
try:
    fugitive = fugitives[user_input]
except KeyError:
    # what do you do when the user enters a bad name?
    # maybe...
    raise

答案 1 :(得分:0)

你是这个意思吗?


import john

def printDict(d):
    # d can be an empty dict
    for k in d:
        print(k, d[k])

tip = "Please enter the name of the fugitive: "
user_input = input(tip)
d = getattr(john, user_input, None)

if (type(d) is dict):   
    printDict(d)
else:
    print("Not a dict or doesn't exist")