Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Dictionary contains List as Value - How to update?

I have a dictionary which has value as a list.

dictionary = {                 'C1' : [10,20,30]                 'C2' : [20,30,40]              } 

Let's say I want to increment all the values in list of C1 by 10, how do I do it?

dictionary.get('C1') gives me the list but how do i update it?

like image 459
Deepak Avatar asked Dec 24 '10 17:12

Deepak


People also ask

How do you update a list of values in a dictionary?

Method 1: Using append() function The append function is used to insert a new value in the list of dictionaries, we will use pop() function along with this to eliminate the duplicate data. Syntax: dictionary[row]['key']. append('value')

Can dictionary values be updated in Python?

Python Dictionary update()The update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.

Can a list be a value in a dictionary Python?

It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.

Can Python dictionary contain list?

A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.


1 Answers

>>> dictionary = {'C1' : [10,20,30],'C2' : [20,30,40]} >>> dictionary['C1'] = [x+1 for x in dictionary['C1']] >>> dictionary {'C2': [20, 30, 40], 'C1': [11, 21, 31]} 
like image 83
Paolo Bergantino Avatar answered Oct 05 '22 19:10

Paolo Bergantino