从python中的for循环中创建的字典中调用数据

时间:2016-12-13 17:03:52

标签: python dictionary

我在从for循环中创建的字典中检索数据时遇到一些问题。在我的代码中,我有两个字典定期创建和更新,一个来自机器数据库,另一个来自全局数据库。我遇到的问题是我需要根据机器编号在一个单独的for循环中评估它们中的每一个。我可以创建字典没问题,但我正在努力使代码在for循环的每次迭代中检索不同的字典标记。

这是创建词典的代码:

# sets machines that need error checking performed
workcenters = ['25294', '25296', '25331', '25334', '25335', '25336']

# Queries local machine database
for index in range(len(workcenters)):
    result = EEDBConnect.connect(workcenters[index])
    globals()["a" + str(workcenters[index])] = result

# Returns a different dictionary for each machine in the form of:
a25294 = {'Line_Status':None, 'Order_ID':None}
a25296 = {'Line_Status':None, 'Order_ID':None}
a25331 = {'Line_Status':None, 'Order_ID':None}
ect....
ect....

# Queries global machine database
for index in range(len(workcenters)):
    result = GBDBConnect.connect(workcenters[index])
    globals()["b" + str(workcenters[index])] = result

# Returns a different dictionary for each machine in the form of: 
b25294 = {'Line_Status':None, 'Order_ID':None}
b25296 = {'Line_Status':None, 'Order_ID':None}
b25331 = {'Line_Status':None, 'Order_ID':None}
ect....
ect....

现在我遇到问题的部分,如何在for循环中查找这些词典?以下只是我尝试做的代码中的一个示例。

(我知道这是完全错误的写作方式,但我找不到更好的方式来描述它)

******更新了******

for index in range(len(workcenters)):
    a = #here is where i need to assign the a##### dictionary 
    b = #here is where i need to assign the b##### dictionary

    stat[str(workcenters[index])] = a['Line_Status'] == b['Line_Status']
    ordr[str(workcenters[index])] = a['Order_ID'] == b['Order_ID'] 

我已经尝试了多种方法来获得理想的结果,而且我已经坚持了这个问题大约一个星期了。我确定这是一个非常愚蠢的东西,我错过了,但我刚刚开始为这个项目编写python,任何帮助都将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

我假设您想要保存在第二个for循环中创建的字典,前缀为b,因为您似乎从最后一个循环的代码中看到了这种方式。< / p>

您的问题就在于此,因为从您当前的代码中可以看出,您使用前缀b创建变量:

# Queries global database
for index in range(len(workcenters)):
    result = GBDBConnect.connect(workcenters[index])
    globals()["b" + str(workcenters[index])] = result  # originally 'a' + ...

另外,请避免使用globals。虽然它看起来很简单有趣,但使用字典来存储动态变量会更好,更简单,更安全。

machine_results = {}
...
machine_results["b" + str(workcenters[index])] = result

P.S。在最后一个循环中,

if a['Line_Status'] == b['Line_Status']:
    result = True
if a['Line_Status'] != b['Line_Status']:
    result = False

可以缩减为

result = a['Line_Status'] == b['Line_Status']

答案 1 :(得分:0)

这是一种可怕的做事方式。而不是将自动生成的项存储在activatedRoute.url.subscribe(() =>{ activatedRoute.snapshot.firstChild.url[0].path }); // is firing only once 工作空间中,其中许多其他变量也会挂起,只需将它们存储在专用命名空间中。换句话说,将您的globals()变量存储在一个a*(可能是dict?)中,将a个变量存储在另一个b*中(可能称为{{ 1}}?)。如有必要,两个dict本身可以是全局变量。我认为绝对 的变量不会被称为b而不是dict(或a1234,无论哪个更有意义)

如果 必须 直接在a[1234]中分配您的变量,当且仅当精神病患者有枪并且坚持要求时,这是可以原谅的,那么问题只是迭代字典并丢弃与预期约定不匹配的键(或者仅处理那些符号的键)。这可以按如下方式完成:

a['1234']