# Formatting arguments into dictionary

**URL:** <https://discuss.python.org/t/formatting-arguments-into-dictionary/57452>\
**Category:** Python Help\
**Created:** [July 6, 2024, 5:40am UTC](https://discuss.python.org/t/formatting-arguments-into-dictionary/57452 "2024-07-06T05:40:14Z")\
**Posts on this page:** 12\
**Page:** 1

<div class="post-metadata">

**Author:** ![dg-pb](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/dg-pb/32/16248_2.png) [@dg-pb](https://discuss.python.org/u/dg-pb)\
**Post date:** [July 6, 2024, 5:40am UTC](https://discuss.python.org/t/formatting-arguments-into-dictionary/57452/1 "2024-07-06T05:40:14Z")

</div>

So I have a function:

```python
def func(a, b, c):
    ... # ?????????
    return attribute_dict

print(func(1, 2, 3))
# {'a': 1, 'b': 2, 'c': 3}

```

Is there any way to return this without needing to manually type `'a', 'b', 'c'` and also not using `**kwds` instead?

---

<div class="post-metadata">

**Author:** ![kknechtel](https://avatars.discourse-cdn.com/v4/letter/k/e47c2d/32.png) [@kknechtel](https://discuss.python.org/u/kknechtel)\
**Post date:** [July 6, 2024, 8:09am UTC](https://discuss.python.org/t/formatting-arguments-into-dictionary/57452/2 "2024-07-06T08:09:59Z")

</div>

If the function is _only_ doing that, it’s trivial:

```python
>>> def func(a, b, c):
... return locals()
... 
>>> func(1, 2, 3)
{'a': 1, 'b': 2, 'c': 3}

```

If you need to figure out which of the `locals()` are the parameter names, you’ll need to do introspection, for example:

```python
import inspect

def func(a, b, c):
    d = None
    return {
        k: v for k, v in locals().items()
        if k in inspect.getargs(func. __code__ ).args
    }

```

Or maybe set up a decorator, so that the wrapper handles the simple case. But then you’ll have to design the way that the decorator holds on to and communicates back the determined `locals()` result.

---

<div class="post-metadata">

**Author:** ![dg-pb](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/dg-pb/32/16248_2.png) [@dg-pb](https://discuss.python.org/u/dg-pb)\
**Post date:** [July 6, 2024, 6:53pm UTC](https://discuss.python.org/t/formatting-arguments-into-dictionary/57452/3 "2024-07-06T18:53:05Z")

</div>

Thank you.

The function is more complex. So `locals()` is not an option.

I am looking for something simpler without using `inspect`.

It is a reoccurring need of mine which I haven’t found solution for yet.

Even if to implement something for it. I don’t even know what could be used for this.

---

<div class="post-metadata">

**Author:** ![zuo](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/zuo/32/11039_2.png) [@zuo](https://discuss.python.org/u/zuo)\
**Post date:** [July 6, 2024, 7:24pm UTC](https://discuss.python.org/t/formatting-arguments-into-dictionary/57452/4 "2024-07-06T19:24:15Z")

</div>

Why not `inspect`? Have you tried [`inspect.signature()`](https://docs.python.org/3/library/inspect.html#inspect.signature) and friends?

For example:

```python
>>> def func(a, b, c=42, *, d, e='E'):
... f = "not a param"
... ...
... bound_arguments = func_sig.bind(**{
... name: val
... for name, val in locals().items()
... if name in func_sig.parameters
... })
... return dict(bound_arguments.arguments)
...     
>>> func_sig = inspect.signature(func)
>>> func(1, b=2, d=7)
{'a': 1, 'b': 2, 'c': 42, 'd': 7, 'e': 'E'}
>>> func(a=1, b=2, c=3, d=7)
{'a': 1, 'b': 2, 'c': 3, 'd': 7, 'e': 'E'}
>>> func(1, 2, 3, d=7, e=8)
{'a': 1, 'b': 2, 'c': 3, 'd': 7, 'e': 8}

```

---

<div class="post-metadata">

**Author:** ![kknechtel](https://avatars.discourse-cdn.com/v4/letter/k/e47c2d/32.png) [@kknechtel](https://discuss.python.org/u/kknechtel)\
**Post date:** [July 6, 2024, 9:10pm UTC](https://discuss.python.org/t/formatting-arguments-into-dictionary/57452/5 "2024-07-06T21:10:06Z")

</div>

> [@zuo](#):
>
> Have you tried [`inspect.signature()`](https://docs.python.org/3/library/inspect.html#inspect.signature) and friends?

Ah, right, was too busy trying to figure out the workaround that I forgot the direct way 🙂

But yes, I really have to question why this is a reoccurring need.

---

<div class="post-metadata">

**Author:** ![dg-pb](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/dg-pb/32/16248_2.png) [@dg-pb](https://discuss.python.org/u/dg-pb)\
**Post date:** [July 6, 2024, 10:19pm UTC](https://discuss.python.org/t/formatting-arguments-into-dictionary/57452/6 "2024-07-06T22:19:36Z")

</div>

> [@zuo](#):
>
> Why not `inspect`? Have you tried [`inspect.signature()`](https://docs.python.org/3/library/inspect.html#inspect.signature) and friends?

Simply too slow and not simple enough.

The way I work around this at the moment is:

```python
NAMES = ['a', 'b', 'c']
def foo(a, b, c):
    return dict(zip(NAMES, [a, b, c]))

```

I am looking for an alternative to this, so desirable solution would ideally improve on this.

So simplicity is satisfiable for the above, but maintenance is a bit annoying as need to keep 2 lists in sync.

> [@kknechtel](#):
>
> But yes, I really have to question why this is a reoccurring need.

It is not this specific case, but a class of problems that I can not seem to find elegant simple way to approach.

See [Mailman 3 Search results for "nameof" - Python-ideas - python.org](https://mail.python.org/archives/search?mlist=python-ideas%40python.org&q=nameof) for examples for `nameof` use cases.

This problem here is `nameof` class problem, but such that even `nameof` can not solve:

```python
print([nameof(i) for i in [a, b, c]])
# ['i', 'i', 'i']

```

So I am just trying to get some opinions, different POVs and possibly solutions that I can not see myself.

---

<div class="post-metadata">

**Author:** ![MegaIng](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/megaing/32/16162_2.png) [@MegaIng](https://discuss.python.org/u/MegaIng)\
**Post date:** [July 6, 2024, 10:32pm UTC](https://discuss.python.org/t/formatting-arguments-into-dictionary/57452/7 "2024-07-06T22:32:36Z")

</div>

If your goal is to just collect the named parameters, you can easily do this with `locals`, even if you are using other variables, just make sure it’s the first thing you do in the function:

```python
def foo(a, b, c):
    args = dict(locals())
    # ... rest of the function
    return args

```

What are the situations where this is an impractical solution?

---

<div class="post-metadata">

**Author:** ![MegaIng](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/megaing/32/16162_2.png) [@MegaIng](https://discuss.python.org/u/MegaIng)\
**Post date:** [July 6, 2024, 10:36pm UTC](https://discuss.python.org/t/formatting-arguments-into-dictionary/57452/8 "2024-07-06T22:36:55Z")

</div>

Oh, I guess that solution doesn’t quite work because `locals` is going to include closure locals and not just the arguments. But still, I am pretty sure this covers most of the already very few situations where this would be helpful.

---

<div class="post-metadata">

**Author:** ![dg-pb](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/dg-pb/32/16248_2.png) [@dg-pb](https://discuss.python.org/u/dg-pb)\
**Post date:** [July 6, 2024, 10:45pm UTC](https://discuss.python.org/t/formatting-arguments-into-dictionary/57452/9 "2024-07-06T22:45:38Z")

</div>

This is possibly as good as it can get for what I need this for at the moment.

---

<div class="post-metadata">

**Author:** ![MegaIng](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/megaing/32/16162_2.png) [@MegaIng](https://discuss.python.org/u/MegaIng)\
**Post date:** [July 6, 2024, 10:49pm UTC](https://discuss.python.org/t/formatting-arguments-into-dictionary/57452/10 "2024-07-06T22:49:54Z")

</div>

Otherwise, here is a completely general function that only uses `sys._getframe`:

```python
def get_args():
    frame = sys._getframe(1)
    total_argcount = frame.f_code.co_argcount + frame.f_code.co_kwonlyargcount
    total_argcount += bool(frame.f_code.co_flags & 4) # Check if we have *args
    total_argcount += bool(frame.f_code.co_flags & 8) # Check if we have **kwargs
    return {
        name: frame.f_locals[name]
        for name in frame.f_code.co_varnames[:total_argcount]
    }

```

This is less cross-version compatible than a solution using `inspect` but that is unavoidable because there is no stability guarantees about these interfaces. But AFAIK, this should work for all currently active python versions.

---

<div class="post-metadata">

**Author:** ![cameron](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/cameron/32/2658_2.png) [@cameron](https://discuss.python.org/u/cameron)\
**Post date:** [July 7, 2024, 1:14am UTC](https://discuss.python.org/t/formatting-arguments-into-dictionary/57452/11 "2024-07-07T01:14:13Z")

</div>

Had you considered writing a decorator? It would inspect the function  
signature (just _once_ when the function gets defined) and wrap it in  
logic to produce the dict at runtime. It even preprovide that dict as an  
additional argument. It’s take a little effort to make it, but once  
you’ve got it…

---

<div class="post-metadata">

**Author:** ![martinberoiz](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/martinberoiz/32/8540_2.png) [@martinberoiz](https://discuss.python.org/u/martinberoiz)\
**Post date:** [July 11, 2024, 12:08am UTC](https://discuss.python.org/t/formatting-arguments-into-dictionary/57452/12 "2024-07-11T00:08:38Z")

</div>

Do you need it to work with arbitrary number of function arguments?  
If not, I think this would work:

```python
>>> def f(a, b, c):
... return dict(a=a, b=b, c=c)
...
>>> f(1, 2, 3)
{'a': 1, 'b': 2, 'c': 3}

```
