Capdi
Capdi

Reputation: 257

how can I pass a list of dictionaries as function parameter?

I have a list that contains a dictionary. A sample of mylist:

products = [{u'title': u'product_A', u'int': [{u'content': 8112, u'name': u'orbitnumber'}, {u'content': 107, u'name': u'relativeorbitnumber'}], u'double': {u'content': 23.4161, u'name': u'cloudcoverpercentage'}]

If I want to find specific items I use a 'for loop'. for example:

for i in range(len(products)):
        unzip(products[i]["title"])

This piece of code works fine. Now, I want to pass that list to a fresh function as a parameter.

How can I define that function that can take 'products' list as argument ? I know that in python you can pass a list as parameter with: *args. But how can I define for example products[list_index]["key"] in a general way in a function.

Upvotes: 1

Views: 5153

Answers (2)

dcampos
dcampos

Reputation: 179

I agree with Toandd. Another way to do it is: 1. define a dictionary with the params you would like to change or include in your dictionary

dictionary = dict(key1=value1,key2=value2)
  1. Pass the dictionary to your function

dictionary_treatment = your_function(dictionary)

It works for me!

Regards

Upvotes: 0

Toandd
Toandd

Reputation: 320

Example your function is my_f You can define it as follow:

def my_f(my_var):
    # then you can do anything you want
    my_var[list_index]["key"] = "0123"
    # Do some other works
    # ...
    # You can return my_var if you need the above change
    return my_var

At other place where you call my_f function and pass "products" as a parameter of my_f function

new_list = my_f(products)

It is just one case to pass parameters. Note that in python you can pass anything as a parameter

Upvotes: 2

Related Questions