Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python-Appending to a list in a dictionary

I've been attempting to add a value to the end of a list inside a dictionary using a different dictionary. The assignment is a little more complicated, so I have simplified the problem down to these three lines, but keep getting None as a result.

finley = {'a':0, 'b':2, 'c':[41,51,61]}
crazy_sauce = {'d':3}
print finley['c'].append(crazy_sauce['d'])
like image 641
Joe Gagliardi Avatar asked Oct 31 '17 03:10

Joe Gagliardi


3 Answers

Your code is fine but print finley['c'].append(crazy_sauce['d']) prints none since finley['c'].append(crazy_sauce['d']) returns none. you remove print here and add a print finley['c'] in next line

finley = {'a':0, 'b':2, 'c':[41,51,61]}
crazy_sauce = {'d':3}
finley['c'].append(crazy_sauce['d'])
print finley['c']
like image 131
Sandeep Lade Avatar answered Oct 04 '22 03:10

Sandeep Lade


You are attempting to print the return value of the .append() function, which is None. You need to print the dict value after the call to .append(), like so:

finley      = {'a':0, 'b':2, 'c':[41, 51 ,61]}
crazy_sauce = {'d':3}

finley['c'].append(crazy_sauce['d'])

print(finley['c'])

Where the output is the following list:

[41, 51, 61, 3]
like image 45
Erick Shepherd Avatar answered Oct 04 '22 04:10

Erick Shepherd


Your solution is correct, but :

Most functions, methods that change the items of sequence/mapping does return None: list.sort, list.append, dict.clear.

So just use print dict in next line after you update the list in dict.

finley = {'a':0, 'b':2, 'c':[41,51,61]}
crazy_sauce = {'d':3}
finley['c'].append(crazy_sauce['d'])
print(finley)
like image 30
Aaditya Ura Avatar answered Oct 04 '22 04:10

Aaditya Ura