0

I have created 2 scripts in python : script 2 contains 3 functions one to create a dictionary second to return a dictionary and third is a random function . and script 1 contains 5 functions fun1 is to call create dictionary function fun2 , fun3 , fun4 are random calculation function and fun5 calls and print the return dictionary function.

Script 1:

from p2 import *

def fun1(keys,values):
    create_map(keys,values)

def fun2(n):
    rand_fun(n)

def fun3(n):
    rand_fun(n)


def fun4(n):
    rand_fun(n)


def fun5(lst):
    print(return_map(lst))

keys = [1,2,3]
values = ['a','b','c']
data = create_map(keys,values)
fun2(2)
fun3(3)
fun4(4)
dictionary = fun5(data)
dictionary1 = fun5(data)
dictionary2 = fun5(data)

Script 2:

def create_map(keys, values):
    return zip(keys,values)

def return_map(data):
    return dict(data)

def rand_fun(n):
    return print((n+1)%2)

The output is:

1
0
1
{1: 'a', 2: 'b', 3: 'c'}
{}
{}

Why am i getting empty dictionary the second and third time and how can i fix this issue

as8400
  • 9
  • 1

2 Answers2

1

reason: zip can only use once.

reference:Python zip object 'disappears' after iterating through?

code:

keys = [1,2,3]
values = ['a','b','c']
data = create_map(keys,values)
fun2(2)
fun3(3)
fun4(4)
dictionary = fun5(create_map(keys,values))
dictionary1 = fun5(create_map(keys,values))
dictionary2 = fun5(create_map(keys,values))

result:

1
0
1
{1: 'a', 2: 'b', 3: 'c'}
{1: 'a', 2: 'b', 3: 'c'}
{1: 'a', 2: 'b', 3: 'c'}
leaf_yakitori
  • 2,232
  • 1
  • 9
  • 21
0

change your create_map function to this.

def create_map(keys, values):
    return dict(zip(keys,values))

like leaf_yakitori said zip can only be used once.

Furkan
  • 352
  • 3
  • 12