1

我在 python 中有一系列从控制文件生成的字典。控制文件只是我们用来解析网页数据的主机名列表。如果主机名列在 url 中,那么我会根据主机名作为键,将整行数据存储在字典中,而行是值。创建各种字典后,我从它们那里得到以下输出。

audit_dicts = {
   "us_osdata":us_osdata, 
   "us_weblogic":us_weblogic, 
   "us_tomcat":us_tomcat
   blah
   blah
   }
for key in audit_dicts:
    print "Length of the %s dictionary is %d lines." % (key, len(audit_dicts[key]))

输出:

Total number of hosts in the control file: 4376
----------------------------------------------------------------------------------------------------
The length of the us_mq dictionary is 266 lines.
The length of the us_oracle dictionary is 198 lines.
The length of the uk_mq dictionary is 59 lines.
The length of the us_osdata dictionary is 765 lines.
The length of the us_websphere_ut dictionary is 137 lines.
The length of the uk_websphere dictionary is 33 lines.
The length of the uk_osdata dictionary is 228 lines.
The length of the uk_oracle dictionary is 41 lines.
The length of the us_weblogic dictionary is 144 lines.
The length of the us_jboss dictionary is 59 lines.
The length of the us_sunweb dictionary is 80 lines.
The length of the us_websphere dictionary is 165 lines.
The length of the us_ihs dictionary is 147 lines.
The length of the us_tcserver dictionary is 0 lines.
The length of the uk_weblogic dictionary is 5 lines.
The length of the us_tomcat dictionary is 236 lines.

我想循环浏览每个主机名的控制文件,并在一行上打印与该主机名相关的所有数据,这些数据存储在 audit_dicts 的字典中。

伪代码 """

for x in control:
        combine = {}
        if x in ** any ** of the audit_dicts[key]
            append values aka lines from all dicts  to combined dictionary
        else
            append x as the key and value.

抱歉,这可能是一个愚蠢的问题,因为我对编程完全陌生。任何帮助将不胜感激。

4

1 回答 1

4

您可以预先组合它们:

from collections import defaultdict

combined = defaultdict(list)

for d in dicts:
    for key, value in d.items():
        combined[key].append(value)

现在,combined包含来自每个字典的值列表。

于 2013-05-20T15:17:09.127 回答