Rasmi Ranjan Nayak
Rasmi Ranjan Nayak

Reputation: 11958

Why the List is not appending the dictionary data into my list?

I have to append the updated dictionary data into list in the below program.

hello = ["hello ", "cruel "]
hi = ["hi", "world"]
myli = []
mydict = {}
def abc():
  for i in xrange(len(hello)):
    for j in xrange(len(hi)):
        mydict["Mydata"] = str(j)
        myli.append( [hello[i], hi[j], mydict])

abc()
print myli

But the output is coming like [['hello ', 'hi', {'Mydata': '1'}], ['hello ', 'world', {'Mydata': '1'}], ['cruel ', 'hi', {'Mydata': '1'}], ['cruel ', 'world', {'Mydata': '1'}]],

where as I am expecting the output like, [['hello ', 'hi', {'Mydata': '0'}], ['hello ', 'world', {'Mydata': '1'}], ['cruel ', 'hi', {'Mydata': '0'}], ['cruel ', 'world', {'Mydata': '1'}]] I can not understand where am I going wrong?

Upvotes: 2

Views: 68

Answers (3)

Daniel
Daniel

Reputation: 42758

You don't create a new dict each time but overwrite the value in the one dict mydict. Simply create a new dict for each list:

def abc(hello, hi):
    myli = []
    for i in xrange(len(hello)):
        for j in xrange(len(hi)):
            myli.append([hello[i], hi[j], {"Mydata": str(j)}])
    return myli

hello = ["hello ", "cruel "]
hi = ["hi", "world"]
print abc(hello, hi)

Upvotes: 2

John La Rooy
John La Rooy

Reputation: 304175

It's convenient to use a list comprehension for this. Notice there is a new dict
{"Mydata": str(j)} created for each item

>>> hello = ["hello ", "cruel "]
>>> hi = ["hi", "world"]
>>> [[x, y, {"Mydata": str(j)}] for x in hello for j, y in enumerate(hi)]
[['hello ', 'hi', {'Mydata': '0'}], ['hello ', 'world', {'Mydata': '1'}], ['cruel ', 'hi', {'Mydata': '0'}], ['cruel ', 'world', {'Mydata': '1'}]]

Upvotes: 1

AkaKaras
AkaKaras

Reputation: 102

the mydict is update to 1, which means it is replaced by 1 instead of 0, and since you are using the mydict and it directly uses the object.

if you put

print myli,mydict

at the end of myli.append( [hello[i], hi[j], mydict]), you will see the result

Upvotes: 1

Related Questions