Home > Software engineering >  Using dict() function to create a dictionary object?
Using dict() function to create a dictionary object?

Time:09-29

I am able to create the dictionary object as follows:

a = dict(name='John', country='Norway')

The gives an output as: {'name': 'John', 'country': 'Norway'}

However, the following statement is throwing an error:

dict([(name, 'John'), (country, 'Norway')])

Error:

NameError: name 'name' is not defined

In both syntax, I am using name and country without quotes but only the second syntax is throwing an error.

The second syntax is working correctly with following code:

a = dict([(1, 'John'), (2, 'Norway')])

Output: {1: 'John', 2: 'Norway'}

CodePudding user response:

Well...

For the first example, this is how it's done:

def dummydict(**kwargs):
    return kwargs

>>> dummydict(a=1, b=2, c=4)
{'a': 1, 'b': 2, 'c': 4}
>>> 

As you can see, **kwargs unpacks the keyword arguments into a dictionary, that's why it works.

As mentioned in the documentation:

**kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function.

For why the second example doesn't work, it is because it gets treated as a variable name, the second one isn't named arguments, it's only tuples in a list, you would have to do:

dict([('name', 'John'), ('country', 'Norway')])
  • Related