Python: Put values of variables into a new dictionary
Question: I am looking for a solution to put the content of 2 variables into a
dictionary. One variable should serve as the key, the other as the value.

Here's my code:

    
    
    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)
    

I would like to have a dictionary with id_data as the keys, and cl_data as the
values without overwriting the old data when appending. How do I go on about
this?

Thanks in advance for any help!


Answer: 
    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)
    

The keys of `d` are the various `id_data`s, and the elements are lists with
elements corresponding to each `id_data` found, in order. Of course, if you
can be sure that all the `id_data`s are unique, you can use a regular
dictionay:

    
    
    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.

