来自另一个模块的Python Dictionary,globals()没有用完

时间:2017-11-03 17:25:59

标签: python dictionary

file1.py

a = {'fullname':'John Wick', 'Age': 35 , 'job':'Hitman'}
b = {'fullname':'Mark Zuckerberg', 'Age': 30, 'job': 'Developer'}
c = {'fullname':'Will smith', 'Age': 45, 'job': 'Actor'}
d = {'fullname':'Messi' , 'Age': 28, 'job' : 'Player'}
so on... and many more details 

注意:dict变量非常不同。 任务是从“姓名”或“工作”等用户输入中获取“年龄” 例如:用户进入梅西......他必须得到28作为输出。

File2.py

from File1.py import *
#what should the code be to access the age 

user_input=raw_input("enter a Name: ")

# user_input contains the name of the person I want to get the Age

我尝试过使用globals(),但这使我的情况变得复杂 它创建一个List,然后必须通过整数访问。

有没有办法搜索dict中的值并与IF条件匹配?

2 个答案:

答案 0 :(得分:0)

是的,有很多方法可以做到这一点,但是这会让情况变得复杂。

首先,进一步简化程序:将远程代码拉入程序文件,并解决那里的访问问题。 运行后,然后将其拆分为第二个文件。

其次,如果您希望这些项目在表单中,您可以轻松搜索,请执行此操作。目前,当你显然希望将它们保持在一起时,你就会把它们分成不同的变量。这有两种方式之一:

(1)简单列表:

people = [
    {'fullname':'John Wick', 'Age': 35 , 'job':'Hitman'},
    {'fullname':'Mark Zuckerberg', 'Age': 30, 'job': 'Developer'},
    {'fullname':'Will smith', 'Age': 45, 'job': 'Actor'},
    {'fullname':'Messi' , 'Age': 28, 'job' : 'Player'}
]

现在,使用常规列表搜索方法查找匹配项。

(2)字典,索引你想要使用它的方式:

people = {
    'John Wick': {'Age': 35 , 'job':'Hitman'},
    'Mark Zuckerberg': {'Age': 30, 'job': 'Developer'},
    'Will smith': {'Age': 45, 'job': 'Actor'},
    'Messi': {'Age': 28, 'job' : 'Player'}
}

这样,您可以通过直接引用people[user_input]获取此人的记录。

这会让你感动吗?

答案 1 :(得分:0)

尝试将file1.py的备份创建为file1.txt并对该文件执行操作

在这里分享一个小有用的片段

import re
user_input=raw_input("enter a Name: ")
with open("file1.txt") as f:
    for line in f:
       #print line
       matches = re.findall(r'\'(.+?)\'', line)
       if user_input in matches:
          age = re.findall(r'\d+', line)
          print age