How to Pass a Dictionary Object as Parameter for a Function in Python

how to pass a dictionary object as parameter for a function in python

You can pass a dictionary as parameter same way the other types of variables:

def prt(test):
#If you call prt with a dictionary as parameter, test will be a dictionary

At difference with other kind of variables, if you modify a dictionary inside the function it will be remain modified outside.

python dictionary passed as an input to a function acts like a global in that function rather than a local

Python's "parameter evaluation strategy" acts a bit different than the languages you're probably used to. Instead of having explicit call by value and call by reference semantics, python has call by sharing. You are essentially always passing the object itself, and the object's mutability determines whether or not it can be modified. Lists and Dicts are mutable objects. Numbers, Strings, and Tuples are not.

You are passing the dictionary to the function, not a copy. Thus when you modify it, you are also modifying the original copy.

To avoid this, you should first copy the dictionary before calling the function, or from within the function (passing the dictionary to the dict function should do it, i.e. testfun4(dict(d)) and defining the function as def testfun4(d):).

How to pass dictionary items as function arguments in python?

If you want to use them like that, define the function with the variable names as normal:

def my_function(school, standard, city, name):
schoolName = school
cityName = city
standardName = standard
studentName = name

Now you can use ** when you call the function:

data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}

my_function(**data)

and it will work as you want.

P.S. Don't use reserved words such as class.(e.g., use klass instead)

Passing dictionary as parameter to a function

Here is a one-liner to map the data to a schema if you can change the schema, you could also just go and grab the keys instead of creating a list of items to match. This formats the data to the schema based on matching keys:

EDIT: added 'Data' tag to the schema and output for nested list data

schema = {
'Global_parameters': [
'clock_frequency', # I noticed you had this as just 'clock' in your desired outuput
'Triggering_Mode'
],
'Executor_param': [
'Mode'
],
'Waveform_Settings': [
'overshoot',
'duty_cycle',
'amplitude/high_level',
'offset/low_level'
],
'Data': {
'Packet'
}
}

data = {
"clock_frequency": 25000,
"Triggering_Mode": "positive_edge_triggered",
"Mode": "Offline",
"overshoot": 0.05,
"duty_cycle": 0.5,
"amplitude/high_level": 1,
"offset/low_level": 0,
"Packet": [
{"time_index":0.1, "data":0x110},
{"time_index":1.21, "data":123},
{"time_index":2.0, "data": 0x45}
]
}

# "one line" nested dict comprehension
data_structured = {k0: {k1: v1 for k1, v1 in data.items() if k1 in v0} # in v0.keys() if you are using the structure you have above
for k0, v0 in schema.items()}

import json
print(json.dumps(data_structured, indent=4)) # pretty print in json format

Output:

{
"Global_parameters": {
"clock_frequency": 25000,
"Triggering_Mode": "positive_edge_triggered"
},
"Executor_param": {
"Mode": "Offline"
},
"Waveform_Settings": {
"overshoot": 0.05,
"duty_cycle": 0.5,
"amplitude/high_level": 1,
"offset/low_level": 0
},
"Data": {
"Packet": [
{
"time_index": 0.1,
"data": 272
},
{
"time_index": 1.21,
"data": 123
},
{
"time_index": 2.0,
"data": 69
}
]
}
}

Pythonic way to pass dictionary as argument with specific keys

You can either use the setattr function:

for k, v in dictionary.items():
setattr(self, k) = v

or simply update the __dict__ attribute of the object:

self.__dict__.update(dictionary)

Passing a dictionary to a function as keyword parameters

Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary

So my example becomes:

d = dict(p1=1, p2=2)
def f2(p1,p2):
print p1, p2
f2(**d)

How to pass a python dictionary to a c function?

Always define .argtypes and .restype for your functions so ctypes can type-check your parameters and know how to marshal them to and from C. py_object is the type to use when passing a Python object directly.

Working example:

// test.c
#include <Python.h>

__declspec(dllexport) // for Windows exports
PyObject *changeDict(PyObject *dict) {
PyObject* value = PyUnicode_FromString("value");
PyDict_SetItemString(dict, "key", value); // Does not steal reference to value,
Py_DECREF(value); // so free this reference
Py_INCREF(dict); // because we're returning it...
return dict;
}
# test.py
from ctypes import *

# Use PyDLL when calling functions that use the Python API.
# It does not release the GIL during the call, which is required
# to use the Python API.
mydll = PyDLL('./test')
mydll.changeDict.argtypes = py_object, # Declare parameter type
mydll.changeDict.restype = py_object # and return value.

dic = {}
x = mydll.changeDict(dic)
print(x)
dic = {'key':2}
mydll.changeDict(dic) # Modified in-place, so really no need to return it.
print(dic)

Output:

{'key': 'value'}
{'key': 'value'}


Related Topics



Leave a reply



Submit