-3

I have a dictionary with a tuple as the key.

my_dictionary[k1, k2] = val

I save the dictionary to a file, but when I read the file back I get an error.

dictionary_from_file = dict(dictionary_file.read())

Error:

ValueError: dictionary update sequence element #0 has length 1; 2 is required
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22

1 Answers1

0

Python dictionary constructor doesn't accept string (or parses it to a new dictionary).

In addition, when having a tuple as key, you can use it as the following:

dict[(t1,t2)]=v

You can take the following steps, and use ast.literal_eval to get back the dictionary from the string representation:

import ast

# Create dictionary
dict1 = dict()

# Set values to tuple keys
dict1[(1,2)] = 'one two'
dict1[(3,4)] = 'three four'

# {(1, 2): 'one two', (3, 4): 'three four'}
dict_string = str(dict1)
print(dict_string)

# Restore dictionary from string with `ast.literal_eval`
dict2 = ast.literal_eval(dict_string)

# {(1, 2): 'one two', (3, 4): 'three four'}
print(dict2)
Aviv Yaniv
  • 6,188
  • 3
  • 7
  • 22