Python Forum

Full Version: Updating dictionary with tuple
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to understand the update method by adding a tuple to a dictionary. Can someone please the Traceback here? I was able to add a list of two tuples but not this one. Thanks!
>>> d
{1: 'one', 2: 'two', 'y': 6}
>>> tuplist2
(4, 9)
>>> d.update(tuplist2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot convert dictionary update sequence element #0 to a sequence
>>>
Here is the documentation of dict.update

Output:
D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
In your case, E = (2, 9) so we are in a case of a sequence that lacks a .keys() method, and the function expects a sequence of pairs, not a sequence of integers.
You could use [(2, 9)] instead of (2, 9)
I'm regularly mixing up parentheses, brackets, and/or lack thereof. Thanks for the help!