0

Problem

I want to unpack some OrderedDict that has lists as values.

from collections import OrderedDict
d = OrderedDict()
d["mark"] = [0,'a']
d["bob"] = [1,'b']
d["mark"] = [0,'c']
d["can"] = [2,'d']

with open("data.txt", 'w+') as data_file:
    for key,value in d:
        if key.startswith("mark"):
            data_file.write("\n")
            data_file.write(str(value[1]) + "\n")
        else:
            data_file.write(key + "=" + str(value[0]) + str(value[1]) + "\n")
    data_file.write("\n")

Error

ValueError: too many values to unpack (expected 2)

SerTet
  • 29
  • 6

1 Answers1

1

with for k, v in d: you are not passing the individual elements of d to k, and v, you are passing d itself and trying to assign it to two variables. You need d.items(), which provides an iterable of the elements inside d:

from collections import OrderedDict
d = OrderedDict()
d["mark"] = [0,'a']
d["bob"] = [1,'b']
d["mark"] = [0,'c']
d["can"] = [2,'d']

with open("data.txt", 'w+') as data_file:
    for key, value in d.items():    # change here
        if key.startswith("mark"):
            data_file.write("\n")
            data_file.write(str(value[1]) + "\n")
        else:
            data_file.write(key + "=" + str(value[0]) + str(value[1]) + "\n")
    data_file.write("\n")
baileythegreen
  • 1,126
  • 3
  • 16