How to use * args in a function to return a list of dictionaries?

Is it possible to use * args to create a list of dictionaries, where each dictionary has the same key and each value is an arg argument?

For example, I have this function:

def Func(word1,word2):
    return [{'This is a word':word1},{'This is a word':word2}]

And I use it like this:

print Func("Word1","Word2")

which returns:

[{'This is a word': 'Word1'}, {'This is a word': 'Word2'}] 

The problem is that I want to use this function with 1 word or 5 words. How can I use * args instead? Will such a function be possible:

def Func(*args):

It would be great if I could create the following, as well as where "This word" has an account like this:

[{'This is a word1': 'Word1'}, {'This is a word2': 'Word2'}] 
+4
source share
3 answers

Rather simple:

def Func(*args):
    return [{'This is a word': arg} for arg in args]


>>> Func('foo', 'bar', 'baz')
[{'This is a word': 'foo'}, {'This is a word': 'bar'}, {'This is a word': 'baz'}]

>>> Func('a', 'b', 'c', 'd', 'e')
[{'This is a word': 'a'}, {'This is a word': 'b'}, {'This is a word': 'c'}, {'This is a word': 'd'}, {'This is a word': 'e'}]

To meet your additional requirements:

def Func(*args):
    return [{'This is a word' + str(i+1): arg} for i, arg in enumerate(args)]


>>> Func('a', 'b', 'c', 'd', 'e')
[{'This is a word1': 'a'}, {'This is a word2': 'b'}, {'This is a word3': 'c'}, {'This is a word4': 'd'}, {'This is a word5': 'e'}]
+1

, , *args,

def Func(*args):
    return [{'This is a word': arg} for arg in args]

print Func("word1")
# [{'This is a word': 'word1'}]

print Func("word1", "word2")
# [{'This is a word': 'word1'}, {'This is a word': 'word2'}]
+1

, - dict?

import collections
def Func2(*args):
    return collections.OrderedDict(('This is a word' + str(i+1), arg) for i, arg in enumerate(args))

>>> Func2('a', 'b', 'c', 'd', 'e')
OrderedDict([('This is a word1', 'a'), ('This is a word2', 'b'), ('This is a word3', 'c'), ('This is a word4', 'd'), ('This is a word5', 'e')])

:

import collections
def Func2(*args):
    return collections.OrderedDict((i+1, arg) for i, arg in enumerate(args))

>>> Func2('a', 'b', 'c', 'd', 'e')
OrderedDict([(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')])

This would make accessing your data objects a little easier, I would think.

>>> foo = Func2('a', 'b', 'c', 'd', 'e')
>>> foo[1]
'a'

And so we see that we have implemented a list accessible by a modifiable index.

+1
source

Source: https://habr.com/ru/post/1523658/


All Articles