Search code examples
pythonstringdictionaryvalueerror

ValueError: too many values to unpack Python when creating Dictionary from a String


I am trying to create a dictionary from a string. In this case I have posted my sample code (sorry its not that clean, just hardcoded values), the first str1 works fine and is able generate a corresponding dictionary by splitting correctly ; and associating key value at = sign.

However, the second string (str5) is not working. I am assuming its because there is an extra "=" at: 1 = '< 24 hours'; 2 = '> 24 hours, <**=** 30 days';

Can you please tell me how I can resolve this issue of ignoring the = sign and continue creating the dictionary. I get the following error:

0=Blank;1=<24hours;2=>24hours,<=30days;3=>30days(i.e.,permanent)
Traceback (most recent call last):

  File xmlread.py:303 in <module>
    main()

  File xmlread.py:299 in main
    stringParseTest()

  File xmlread.py:283 in stringParseTest
    key, value = pair.split("=")

ValueError: too many values to unpack (expected 2)

I could try parsing it manually and not create a dictionary; however I would like to see if there is a condition I could add in there to recognize this issue. Don't know how to do that though.

What if I add an if statement to check how many times a string has been splitted.

def stringParseTest():
    str1 = str("0 = Blank; 1 = Surface Device: Skin; 2 = Surface Device: Mucosal Membrane; 3 = Surface Device: Breached or Compromised Surfaces; 4 = External Communicating Device: Blood Path, Indirect; 5 = External Communicating Device: Tissue/Bone/Dentin; 6 = External Communicating Device: Circulating Blood; 7 = Implant Device: Tissue/Bone; 8 = Implant Device: Blood")

    str5 = str("0 = Blank; 1 = '< 24 hours'; 2 = '> 24 hours, <= 30 days'; 3 = '> 30 days (i.e., permanent)'")
    

    dictionary = {}
    
    #Working string split
    str1 = str1.replace(" ", "")
    str1 = str1.replace("'", "")
    print(str1)
    for pair in str1.split(";"):
        key, value = pair.split("=")
        dictionary[key] = value
    print(dictionary)   

    
    #Not working split
    str5 = str5.replace(" ", "")
    str5 = str5.replace("'", "")
    print(str5)
    for pair in str5.split(";"):
        key, value = pair.split("=")
        dictionary[key] = value
    print(dictionary)

Solution

  • In split function you can pass additional parameter like maxsplit=1, so that it will split only based on first occurence of delimiter. i.e.g pair.split("=", 1)

    for pair in str5.split(";"):
        key, value = pair.split("=", 1)
        dictionary[key] = value