我正在尝试迭代看起来像这样的字典:
d = { "list_one": [ "hello", "two", "three" ], "list_two": [ "morning", "rain" ] }我正在使用这个功能:
def combine_words(d): for k, v in d.items(): a = {k: ("|".join(v))} return a当我用print运行它时,我的输出只是一个键,值对。 我不确定这里发生了什么。 我的理想出局是:
{ 'list_one': 'hello|two|three', 'list_two': 'morning|rain' }I'm trying to iterate through a dictionary that looks like:
d = { "list_one": [ "hello", "two", "three" ], "list_two": [ "morning", "rain" ] }I'm using the function:
def combine_words(d): for k, v in d.items(): a = {k: ("|".join(v))} return aWhen I run this with print, my output is just one key, value pair. I'm not sure what is happening here. My ideal out put would be:
{ 'list_one': 'hello|two|three', 'list_two': 'morning|rain' }最满意答案
每次循环都会被一个新的dict取代。 你想要一个词典理解。
def combine_words(d): return {k: "|".join(v) for k, v in d.items()}a gets replaced by a new dict each time through your loop. You want a dict comprehension.
def combine_words(d): return {k: "|".join(v) for k, v in d.items()}通过列表作为值迭代python字典(Iterating through a python dictionary with lists as values)我正在尝试迭代看起来像这样的字典:
d = { "list_one": [ "hello", "two", "three" ], "list_two": [ "morning", "rain" ] }我正在使用这个功能:
def combine_words(d): for k, v in d.items(): a = {k: ("|".join(v))} return a当我用print运行它时,我的输出只是一个键,值对。 我不确定这里发生了什么。 我的理想出局是:
{ 'list_one': 'hello|two|three', 'list_two': 'morning|rain' }I'm trying to iterate through a dictionary that looks like:
d = { "list_one": [ "hello", "two", "three" ], "list_two": [ "morning", "rain" ] }I'm using the function:
def combine_words(d): for k, v in d.items(): a = {k: ("|".join(v))} return aWhen I run this with print, my output is just one key, value pair. I'm not sure what is happening here. My ideal out put would be:
{ 'list_one': 'hello|two|three', 'list_two': 'morning|rain' }最满意答案
每次循环都会被一个新的dict取代。 你想要一个词典理解。
def combine_words(d): return {k: "|".join(v) for k, v in d.items()}a gets replaced by a new dict each time through your loop. You want a dict comprehension.
def combine_words(d): return {k: "|".join(v) for k, v in d.items()}
发布评论