0

I know the title seems easy but I've tried multiple ways and I was not able to achieve what I want.

I tried different ways, I looked into similar questions here and I tried their solutions yet I was not able to get it to work.

I'm trying to filter a list then return a dictionary with containing dictionary (json)

def clean_content(data):
    single = {}
    cdata = {}
    for i in range(len(data):
        single.clear()
        single['id'] = data[i]['id']
        single['title'] = data[i]['title']
        single['url'] = data[i]['alternate'][0]['href']
        cdata[i] = single
    print(cdata)

this print the same value for each cdata:

{0: {'id': '456', 'title': 'def', 'url': 'https'}, 1: {'id': '456', 'title': 'def', 'url': 'https'}}

notice the index 0,1 have the same exact value.

if I try to print(single) inside the loop:

{'id': '123', 'title': 'abc', 'url': 'http'}

{'id': '456', 'title': 'def', 'url': 'https'}

it shows me a different value which make sense but I'm not sure why the final result shows duplicate of the last value of single.

I tried cdata.update({i:single}) instead of = and still the same issue.

I tried different approaches, array instead of dictionaries

def clean_content(data):
    single = {}
    cdata = []
    for i in range(3):
        single.clear()
        single['id'] = data[i]['id']
        single['title'] = data[i]['title']
        single['url'] = data[i]['alternate'][0]['href']
        cdata.append(single)
    print(cdata)

and I get the same results! the list contain just duplicates of the last element Can someone tell me what am I missing here?

Cœur
  • 37,241
  • 25
  • 195
  • 267
0x2bad
  • 308
  • 2
  • 11
  • 2
    Your problem is that you're storing _the same dictionary_ under every key. When you do `single.clear()`, that clears out the same dictionary that's stored under every key. When you do `single['id'] = data[i]['id']`, that adds a new key-value pair to the same dictionary that's stored under every key. And so on. What you want to do is to create a separate dictionary for each key. Just move the `single = {}` inside the loop, and get rid of the `single.clear()`. – abarnert Aug 29 '18 at 06:01
  • Can you add the `data`? – SanthoshSolomon Aug 29 '18 at 06:03

0 Answers0