Trying to define function that calls keys from a pickle file

Viewed 44

So I'm trying to define a function that takes a pickle file and one or more keys as parameters and then returns the values for the keys called from said pickle file. I'm having trouble figuring out how to call multiple keys within the function. This is what I have so far:

import pickle

def read_keys(picklefile, keys):
    file = open(picklefile, "rb")
    loaded_dictionary = pickle.load(file)

    for key in loaded_dictionary.keys:
        if key in keys:
            return 
        
    if "Name" in loaded_dictionary:
        name = loaded_dictionary["Name"]
    else:
        name = None
        
    if "City" in loaded_dictionary:
        city = loaded_dictionary["City"]
    else:
        city = None
        
    if "Address" in loaded_dictionary:
        address = loaded_dictionary["Address"]
    else:
        address = None
    return
        

print(read_keys('isabel.pickle', ['Name'], ['City']))
print(read_keys('mamadou.pickle', ['Name'], ['City'], ['Address']))

I keep getting this error:

    `---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-4-2bbef15443a2> in <module>
         26 
         27 
    ---> 28 print(read_keys('isabel.pickle', ['Name'], ['City']))
         29 print(read_keys('mamadou.pickle', ['Name'], ['City'], ['Address']))

TypeError: read_keys() takes 2 positional arguments but 3 were given

`

3 Answers

Your function definition:

def read_keys(picklefile, keys):

Your function call:

read_keys('isabel.pickle', ['Name'], ['City'])

The error is obvious because the number of parameters do not match

The read_keys method can be modified as:

  • Pass the list of required keys as a list. (e.g.: ['Name', 'City'])
  • Declare an empty dictionary (here: data) in the read_keys method.
  • If they are available in the pickle file then, add the key and its value to the previously declared dictionary.

Here is an example reading and writing dictionary in pickle file:

import pickle

def write_keys(picklefile, data):
    file = open(picklefile, "wb")
    pickle.dump(data, file)
    file.close()    
    return "{} is written successfully".format(picklefile)

def read_keys(picklefile, keys):
    file = open(picklefile, "rb")
    loaded_dictionary = pickle.load(file)
    data = {}
    for key in keys:
        if key in loaded_dictionary.keys():
            data[key] = loaded_dictionary[key]
    file.close()
    return data

print(write_keys('isabel.pickle',
                 {'Name': 'Isabel', 'City': 'Dhaka'}))
print(write_keys('mamadou.pickle',
                 {'Name': 'Mamadou',
                  'City': 'Sylhet',
                  'Address': 'Sadar'}))
print(read_keys('isabel.pickle', ['Name', 'City']))
print(read_keys('mamadou.pickle', ['Name', 'City', 'Address']))

Output:

isabel.pickle is written successfully
mamadou.pickle is written successfully
{'Name': 'Isabel', 'City': 'Dhaka'}
{'Name': 'Mamadou', 'City': 'Sylhet', 'Address': 'Sadar'}

Since the keys argument is a sequence, you need to pass it as a single value when calling the function. In addition you need to sequentially process each one of them in the function. The dictionary get() method makes retrieving the associated values if they exist easy, as well as providing a default value when they aren't.

The following shows how to do both:

import pickle

def read_keys(picklefile, keys):
    with open(picklefile, "rb") as file:
        loaded_dictionary = pickle.load(file)
    return [loaded_dictionary.get(key, 'None') for key in keys]


print(read_keys('isabel.pickle', ('Name', 'City')))
print(read_keys('mamadou.pickle', ('Name', 'City', 'Address')))
Related