Python Forum
Updating dictionary with tuple
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Updating dictionary with tuple
#1
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
>>>
Reply
#2
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)
Reply
#3
I'm regularly mixing up parentheses, brackets, and/or lack thereof. Thanks for the help!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  convert a named tuple to a dictionary Skaperen 13 3,388 Mar-31-2022, 07:13 PM
Last Post: Skaperen
  code with no tuple gets : IndexError: tuple index out of range Aggam 4 2,727 Nov-04-2020, 11:26 AM
Last Post: Aggam
  updating a dictionary evansmb 2 2,292 Feb-20-2020, 10:08 AM
Last Post: perfringo
  How to get first line of a tuple and the third item in its tuple. Need Help, Anybody? SukhmeetSingh 5 3,121 May-21-2019, 11:39 AM
Last Post: avorane
  Converting List of 3 Element Tuple to Dictionary fooikonomou 11 5,707 Jan-14-2019, 09:51 AM
Last Post: perfringo
  Updating dictionary values Sukumar 2 2,414 Oct-03-2018, 09:53 PM
Last Post: Sukumar
  create dictionary from **kwargs that include tuple bluefrog 2 4,820 Oct-26-2016, 10:24 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020