Python 3使用用户输入来访问另一个文件中的字典

问题描述 投票:0回答:2

我想获取用户输入(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])
python dictionary input
2个回答
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")

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
© www.soinside.com 2019 - 2024. All rights reserved.