【问题标题】:Given a dictionary, how do I join the key and value with "_" and append them into a list?给定一个字典,我如何用“_”连接键和值并将它们附加到列表中?
【发布时间】:2020-10-09 09:42:36
【问题描述】:

我有以下几点:

def dict_join_key_value(input_dict):
    for key,value in input_dict.items():
        y=[]
        x=key+'_'+value
        print(y.append(x))
    return 
dict_join_key_value({"a": "b", "c": "d"})

我无法生成列表 ['a_b','c_d'],我需要对我的代码进行哪些更改?

【问题讨论】:

  • 您每次都在重置您的列表。将 y=[] 移到 for 循环之外
  • 另外,你不会返回y
  • 不要在每个循环中将列表重置为空列表。另外,不要打印append 的返回值。并返回y

标签: python list dictionary append


【解决方案1】:

正如在 cmets 中指出的那样,以下方法将起作用:

def dict_join_key_value(input_dict):
    y = []
    for key,value in input_dict.items():
        x = key + '_' + value
        y.append(x)
    return y

dict_join_key_value({"a": "b", "c": "d"})

你可以在理解中缩短它:

def dict_join_key_value(input_dict):
    return [k + '_' + v for k, v in input_dict.items()]

或者使用map:

def dict_join_key_value(input_dict):
    return list(map('_'.join, input_dict.items()))

【讨论】:

    猜你喜欢
    • 2020-04-09
    • 2019-10-06
    • 2023-03-23
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    相关资源
    最近更新 更多