user1893110
user1893110

Reputation: 271

Updating dictionary with loop

Given a dict like so:

d = {'pens': (3, 0), 'cups': (2, 0), 'coins': (7, 0)}

I am trying to access the key to update the 2nd attirbute e.g.

for x,y,z in d.items():
    if x=='pens'
       z=5

Why does this not work? What is a solution that does?

Upvotes: 1

Views: 6270

Answers (6)

Chris
Chris

Reputation: 22953

The reason your solution couldn't work is because tuples are immutable, which means there contents cannot be changed. There similar. constants in other language. Furthermore, .items() returns a two tuple pair, so trying to unpack it with three variables should have raised an error.

With that said, You can make use of dictionary comprehension, and Python's ternary operator:

>>> d = {'pens': (3, 0), 'cups': (2, 0), 'coins': (7, 0)}
>>> d = {key: (val[0], 5) if key == 'pens' else val for key, val in d.items()}
>>> d
{'pens': (3, 5), 'cups': (2, 0), 'coins': (7, 0)}
>>> 

Upvotes: 3

Bill Gribble
Bill Gribble

Reputation: 1797

You have a couple of problems here.

First, items() returns an iterable whose elements are 2-element tuples, with the first of each tuple being the key and the second being the value.

In your case, you need to unpack the "value" tuple further:

for x, value in d.items():
  y, z = value

Second, it looks like you are trying to update the dict with your new value ("5"), but you just have a copy of the element, and the value type itself is a tuple, which is immutable. You can't change a single element of the tuple. So you will have to replace the entire value tuple in the dict with a new tuple:

for x, value in d.items():
    y, z = value
    if x == 'pens':
        d[x]  = (y, 5)

Note that updating a dict or list while you are iterating over it can be a problem in some cases. Be careful.

Upvotes: 1

Falloutcoder
Falloutcoder

Reputation: 1011

Well you cannot update a tuple(the values in the dictionary), as tuples are immutable so you will have to assign the key new tuple. Other thing wrong with this loop is the way tuple is unpacked. It should be like this

for x,(y,z) in d.items():
    if x=='pens':
       d[x] = (y, 5)

Upvotes: 1

Aidenhjj
Aidenhjj

Reputation: 1289

Just do:

d = {'pens': (3, 0), 'cups': (2, 0), 'coins': (7, 0)}
if 'pens' in d:
    d['pens'] = (d['pens'][0], 5)

Upvotes: 3

user3030010
user3030010

Reputation: 1857

z is only temporarily bound to the value that you get from the second part of the tuple; it is not a reference back to the tuple itself. You have to find the tuple within the original dict, then update it (which is complicated by the fact that tuples are immutable). Try something like this:

for x, (y, z) in d.items():
    if x == 'pens':
        d[x] = (y, 5)

Upvotes: 3

Fejs
Fejs

Reputation: 2888

Because You're not changing it in dictionary. You could do it this way:

if "pens" in d.keys():
    d["pens"] = (d["pens"][0], 5)

Upvotes: 1

Related Questions