-1

I am trying to create a list of dictionaries, but everytime when I try to append a new item to the list, it is replacing the previous copies with then new item.

nested_dict = {}

request_data = { 
        "locale": "US",
        "field": "Company Name",
        "document_type": "invoice"
    }


for key, value in request_data.items():
    term_item = {}
    term_item[key] = value
    nested_dict["term"] = term_item
    term_list.append(nested_dict)

Result obtained:

[{'term': {'document_type': 'invoice'}}, {'term': {'document_type': 'invoice'}}, {'term': {'document_type': 'invoice'}}]

Expectation :

[{'term': {"locale": "US"}}, {'term': {"field": 'Company Name'}}, {'term': {'document_type': 'invoice'}}]
Tom J Muthirenthi
  • 3,028
  • 7
  • 40
  • 60

1 Answers1

3

is that what you were looking for?

request_data = { 
        "locale": "US",
        "field": "Company Name",
        "document_type": "invoice"
    }

print([{'term': {key,value}} for key,value in request_data.items()])

output:

[{'term': {'US', 'locale'}}, {'term': {'Company Name', 'field'}}, {'term': {'document_type', 'invoice'}}]
Yossi Levi
  • 1,258
  • 1
  • 4
  • 7
  • 1
    I think he was looking for an explanation of why is current code is not working... – Tomerikoo Sep 29 '20 at 07:20
  • @Tomerikoo - If you can write it as an answer, will accept it – Tom J Muthirenthi Sep 29 '20 at 07:25
  • @TomJMuthirenthi I have provided a link above which should answer you. Although it deals with lists, the idea is the same. TL;DR: you re-use the same `nested_dict` object and add it to the list many times. So your list is just many references to the same dict. This is why you see just the last values. Simply move the `nested_dict = {}` to be inside the loop to create a new dict with each iteration. Then, you can start working on making the loop more compact, as suggested above – Tomerikoo Sep 29 '20 at 07:32