Sign Up

Have an account? Sign In Now

Sign In

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have a permission to ask a question, You must login to ask question.

Forgot Password?

Need An Account, Sign Up Here
Sign InSign Up

ErrorCorner

ErrorCorner Logo ErrorCorner Logo

ErrorCorner Navigation

  • Home
  • Contact Us
  • About Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Contact Us
  • About Us
Home/ Questions/Q 609
Next
Answered
Kenil Vasani
Kenil Vasani

Kenil Vasani

  • 646 Questions
  • 567 Answers
  • 77 Best Answers
  • 26 Points
View Profile
  • 5
Kenil Vasani
Asked: December 14, 20202020-12-14T21:07:02+00:00 2020-12-14T21:07:02+00:00In: Python

Python – How to fix “ValueError: not enough values to unpack (expected 2, got 1)”

  • 5
Closed. This question needs debugging details. It is not currently accepting answers.


Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Closed 2 years ago.


Improve this question

I need to write a function add_to_dict(d, key_value_pairs) which adds each given key/value pair to a python dictionary. The argument key_value_pairs will be a list of tuples in the form (key, value).

The function should return a list of all of the key/value pairs which have changed (with their original values).

def add_to_dict(d, key_value_pairs):

   newlist = []

   for key,value in d:
       for x,y in key_value_pairs:
           if x == key:
              newlist.append(x,y)
            
   return newlist

I keep getting an error

ValueError: not enough values to unpack (expected 2, got 1)

How do I solve this error?

dictionarypython
  • 1 1 Answer
  • 14 Views
  • 0 Followers
  • 0
Answer
Share
  • Facebook

    1 Answer

    • Voted
    1. Kenil Vasani

      Kenil Vasani

      • 646 Questions
      • 567 Answers
      • 77 Best Answers
      • 26 Points
      View Profile
      Best Answer
      Kenil Vasani
      2020-12-14T21:02:23+00:00Added an answer on December 14, 2020 at 9:02 pm

      How you should debug your code

      '''
      @param d: a dictionary
      @param key_value_pairs: a list of tuples in the form `(key, value)`
      @return: a list of tuples of key-value-pair updated in the original dictionary
      '''
      def add_to_dict(d, key_value_pairs):
      
          newlist = []
      
          for pair in key_value_pairs:
      
              # As is mentioned by Mr Patrick
              # you might not want to unpack the key-value-pair instantly
              # to avoid possible corrupted data input from
              # argument `key_value_pairs`
              # if you can't guarantee its integrity
              try:
                  x, y = pair
              except (ValueError):
                  # unable to unpack tuple
                  tuple_length = len(pair)
                  raise RuntimeError('''Invalid argument `key_value_pairs`!
                      Corrupted key-value-pair has ({}) length!'''.format(tuple_length))
      
              # Instead of using nesting loop
              # using API would be much more preferable
              v = d.get(x)
      
              # Check if the key is already in the dictionary `d`
              if v:
                  # You probably mean to append a tuple
                  # as `array.append(x)` takes only one argument
                  # @see: https://docs.python.org/3.7/library/array.html#array.array.append
                  #
                  # Besides, hereby I quote
                  # "The function should return a list of all of the key/value pairs which have changed (with their original values)."
                  # Thus instead of using the following line:
                  #
                  # newlist.append((x, y,))
                  #
                  # You might want a tuple of (key, old_value, new_value)
                  # Hence:
                  newlist.append((x, v, y,))
      
              # I don't know if you want to update the key-value-pair in the dictionary `d`
              # take out the following line if you don't want it
              d[x] = y
      
          return newlist
      

      Please keep reading the remaining part if you want to know how to traverse a dict object properly.


      Different ways to traverse a dict object

      Python 3.x

      The following segments demonstrate how to traverse a dict in Python 3.x.

      Iterate the set of keys

      for key in d:
          value = d[key]
          print(key, value)
      
      the code segment above has the same effect as the following one:
      
      for key in d.keys():
          value = d[key]
          print(key, value)
      

      Iterate the set of key-value-pairs

      for key, value in d.items():
          print(key, value)
      

      Iterate the set of values

      for value in d.values():
          print(value)
      

      Python 2.x

      The following segments demonstrate how to traverse a dict in Python 2.x.

      Iterate the set of keys

      for key in d:
          value = d[key]
          print(key, value)
      

      keys() returns a list of the key set of dictionary d

      for key in d.keys():
          value = d[key]
          print(key, value)
      

      iterkeys() returns an iterator of the key set of dictionary d

      for key in d.iterkeys():
          value = d[key]
          print(key, value)
      

      Iterate the set of key-value-pairs

      values() returns a list of the key-value-pair set of dictionary d

      for key, value in d.items():
          print(key, value)
      

      itervalues() returns an iterator of the key-value-pair set of dictionary d

      for key, value in d.iteritems():
          print(key, value)
      

      Iterate the set of values

      values() returns a list of the value set of dictionary d

      for value in d.values():
          print(value)
      

      itervalues() returns a iterator of the value set of dictionary d

      for value in d.itervalues():
          print(value)
      

      Reference:

      • What is the difference between list and iterator in Python?
      • 0
      • Share
        Share
        • Share on Facebook
        • Share on Twitter
        • Share on LinkedIn
        • Share on WhatsApp

    You must login to add an answer.

    Forgot Password?

    Sidebar

    Ask A Question
    • Popular
    • Kenil Vasani

      SyntaxError: invalid syntax to repo init in the AOSP code

      • 5 Answers
    • Kenil Vasani

      xlrd.biffh.XLRDError: Excel xlsx file; not supported

      • 3 Answers
    • Kenil Vasani

      Homebrew fails on MacOS Big Sur

      • 3 Answers
    • Kenil Vasani

      runtimeError: package fails to pass a sanity check for numpy ...

      • 3 Answers
    • Kenil Vasani

      Replicating claims as headers is deprecated and will removed from ...

      • 2 Answers

    Explore

    • Most Answered
    • Most Visited
    • Most Voted
    • Random

    © 2020-2021 ErrorCorner. All Rights Reserved
    by ErrorCorner.com