1

我正在寻找将 2 个变量的内容放入字典的解决方案。一个变量应该作为键,另一个作为值。

这是我的代码:

dom = parseString(data)
macro=dom.getElementsByTagName('macro')
for node in macro:
    d={}
    id_name=node.getElementsByTagName('id')[0].toxml()
    id_data=id_name.replace('<id>','').replace('</id>','')
    print (id_data)
    cl_name=node.getElementsByTagName('cl2')[0].toxml()
    cl_data=cl_name.replace('<cl2>','').replace('</cl2>','')
    print (cl_data)

我想要一个以 id_data 作为键,以 cl_data 作为值的字典,而不会在追加时覆盖旧数据。我该怎么做呢?

提前感谢您的帮助!

4

1 回答 1

2
from collections import defaultdict

d=defaultdict(list)

dom = parseString(data)
macro=dom.getElementsByTagName('macro')
for node in macro:
    id_name=node.getElementsByTagName('id')[0].toxml()
    id_data=id_name.replace('<id>','').replace('</id>','')
    print (id_data)
    cl_name=node.getElementsByTagName('cl2')[0].toxml()
    cl_data=cl_name.replace('<cl2>','').replace('</cl2>','')
    print (cl_data)
    d[id_data].append(cl_data)

的键d是各种id_datas,元素是列表,其中每个id_data找到的元素按顺序对应。当然,如果您可以确定所有id_datas 都是唯一的,则可以使用常规字典:

d={}
for node in macro:
    ...
    d[id_data]=cl_data

This differs from your original code in that I pulled the dictionary constructor out of the loop (You don't want to replace your dictionary each time in the loop) and actually I actually insert the elements into the dict although I'm guessing you did that too, you just don't show it.

于 2012-07-16T14:00:39.760 回答