Python3使用用户输入访问另一个fi中的字典

2024-04-25 04:16:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用users输入(current_input)并使用它访问名为(john)的字典,该字典位于一个名为(约翰·皮伊). 如果用户输入john,我希望检查for语句约翰。约翰并打印出键(x)和属性(约翰。约翰[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])

(编辑) 最初的代码是:

^{pr2}$

Tags: the用户importforinput字典属性语句
2条回答

你是说这个吗?在


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")

你不想这么做。这是初学者常犯的一个错误,即将的意思赋给变量名。不要让你的有意义,但你的变量名应该是好的、描述性的名称,程序员可以清楚地知道,但对程序来说没有任何意义。在

很可能,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

相关问题 更多 >