Naveen
Naveen

Reputation: 788

Appending Python Lists to Dictionary

I am trying to find if a tag is present in a list and then map them to a dictionary and add them to the corresponding tag. This is what I came up with.

RequiredTags = ['PolicyNumber', 'PaymentAmt', 'PolicyAmt']
ListOfTags = ['Header', 'Version','PolicyNumber', 'PaymentAmt', 'Body', 'PolicyAmt']
ListOfValues = ['', '1.1', '123456', '100.00', '', '1']

values = dict.fromkeys(RequiredTags, [])
for key, value in values.items():
    if key in ListOfTags:
        v = ListOfValues[ListOfTags.index(key)]
        print(key, v)
        values[key].append(v)

The problem is, everytime a value is appended, it is appended to every key in the dictionary and not just the one which I'm trying to append to.

Expected output is like

values = {'PolicyNumber': ['123456'], 'PaymentAmt': ['100.00'], 'PolicyAmt': ['1']}

I have a list of xml files, i want to extract and export values from.

This will add the values to the dict for one file but I want to append the values from all XML files to this one dictionary. Hope this clarifies the question better.

Upvotes: 0

Views: 3143

Answers (1)

user
user

Reputation: 46

Your question doesn't seem to make much sense but what I inferred was that the required output should correspond to the list of required tags.

values = dict.fromkeys(RequiredTags)
for i, tag in enumerate(ListOfTags):
    if tag in RequiredTags:
        values[tag] = ListOfValues[i]

which returns the following:

{'PaymentAmt': '100.00', 'PolicyAmt': '1', 'PolicyNumber': '123456'}

Hope this is what you wanted.

EDIT:

So, this is what I think you want:

values = {}
for i, tag in enumerate(ListOfTags):
    if tag in RequiredTags:
        values.setdefault(tag, []).append(ListOfValues[i])

In the last line if the key exists in the dict, then it appends to the list of values otherwise it initialises the value with an empty array.

Upvotes: 3

Related Questions