Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary won't update with a string as key

I'm trying to update a dictionary using a function returning a tuple where the first element is a string.

>>> def t():
...     return 'ABC', 123

However the dict.update function does not quite like it.

>>> d = {}
>>> d.update(t())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 3; 2 is required

I can also try dictionary comprehension and get the same unexpected result.

>>> d.update({k: v for k, v in t()})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <dictcomp>
ValueError: too many values to unpack (expected 2)

The only working way is to first save returned value.

>>> x = t()
>>> d.update({x[0]: x[1]})
>>> d
{'ABC': 123}

How to explain this?

like image 670
Spack Avatar asked Mar 09 '23 23:03

Spack


1 Answers

From the docs

update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2).

For example:

In [1]: d = {}

In [2]: def t(): return [('ABC', '123')]

In [3]: d.update(t())

In [4]: d
Out[4]: {'ABC': '123'}

In [5]: d2 = {}

In [6]: def t2(): return {'ABC': '123'}

In [7]: d2.update(t2())

In [8]: d2
Out[8]: {'ABC': '123'}
like image 107
Jack Avatar answered Mar 19 '23 21:03

Jack