-2

How can I call a dictionary created in one function to another?

I have tried using How do I access a dictionary from a function to be used in another function? but it doesn't work for me.

I have created dictionary1 in server() and I want to use it in create_csv().

How can I call it?

def server(id):

  dictionary1 = dict(zip(temp_sourcenodes, sip))

  dictionary1.update(dict(zip(temp_destnodes, dip)))

  print(dictionary1)

def create_csv():
jpp
  • 159,742
  • 34
  • 281
  • 339
Sakshi
  • 17
  • 1
  • 6

1 Answers1

3

Use return and call server from within create_csv. This may necessitate feeding id_ to create_csv, but this is likely reasonable, as presumably dictionary1 is constructed based on id_.

def server(id_):
    # some code to construct dictionary1
    return dictionary1

def create_csv(id_):
    my_dict = server(id_)
    # export to csv here
jpp
  • 159,742
  • 34
  • 281
  • 339
  • no the dictionary is not based on id. temp_sourcenodes and sip are two lists. I am using one as key and other as value. – Sakshi Jan 31 '19 at 10:30
  • @Sakshi, The code will still work irrespective. Otherwise, if the dictionary construction doesn't need `id_`, create it in another function that doesn't require `id_` as an argument. – jpp Jan 31 '19 at 10:59
  • @Sakshi, Yet another alternative is to use object-oriented programming to store class-instance-level variables. – jpp Jan 31 '19 at 11:04
  • Yes, just make sure you provide all necessary arguments when you call `server`. – jpp Jan 31 '19 at 13:43
  • but its not working if i call id in create_csv and i cant remove id from server() – Sakshi Jan 31 '19 at 15:23