Is it possible to use *args to produce a list of dictionaries where each dictionary has the exact same key and each value is the arg?

For example, I currently have this function:

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

And I use it like so:

print Func("Word1","Word2")

which returns:

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

The issue is that I want to use this Function with 1 word or 5 words. How could I use *args instead? Would starting a function like this be possible:

def Func(*args):

It would be amazing if I could produce the following as well where "This is a word" has the count like so:

[{'This is a word1': 'Word1'}, {'This is a word2': 'Word2'}] 
有帮助吗?

解决方案

Rather simple to do:

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 requirement:

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'}]

其他提示

You can use list comprehension to create a new list of dictionaries by iterating over the *args, like this

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'}]

Looks like you might be going for something like an ordered 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')])

Or just:

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 bit easier, I would think.

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

And in this way we see we've implemented a sort of list accessible by a modifiable index.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top