将列表字典的值与嵌套字典连接起来

Concatenate values of dictionary of list with nested dictionaries

我想从以下字典中提取值 A、C、D 和 E(我不需要 value_B,它是一个数字):

{'key1': [{'key_A': 'value_A', 'key_B': value_B}, 
         {'key_A': 'value_C'},
         {'key_A': 'value_D'},
         {'key_A': 'value_E'}],
'key2': True}

然后我想将这些值连接成一个字符串,每个值之间换行。 像这样:

string = ''
for value in values:
    string += value + '\n' 

或者这样:

string = ''
string = '\n'.join(values)

我要的是这个:

string = 'value_A' + '\n' + 'value_C' + '\n' + 'value_D' + '\n' + 'value_E'

执行此操作的最佳方法是什么?我会怎么做呢? 我什至不知道从哪里开始。

虽然您可以在一行中完成此操作,但我建议将您的问题分解为更小的子问题。

my_string = '\n'.join(e['key_A'] for e in my_dict['key1'])

你有一本字典,其中一个键包含一个字典列表。您希望最终得到一个字符串,其中包含字典列表中每个字典的 'key_A' 的值,由 '\n' 分隔。

对我来说明显的步骤是:

  1. Select 来自父字典 'key1' 的字典列表。
  2. 从字典列表中收集 'key_A' 的值
  3. 将值连接到一个由“\n”分隔的字符串中
# Select the list of dicts from the parent dict
my_list_of_dicts = my_dict['key1']

# Select the 'key_A' value from each dict in the list
my_values = [e['key_A'] for e in my_list_of_dicts]

# Join the values together into a string separated by the '\n'
my_string = '\n'.join(my_values)

如果您直到运行时才知道使用什么键,并且您确信第一个键就是所需的键。您可以预先导出密钥并存储它,也可以为每个单独的字典导出它。

# Derive the key in advance
# Get the first key of the first dict stored in my_dict['key1']
my_key = list(my_dict['key1'][0].keys())[0]
my_string = '\n'.join(e[my_key] for e in my_dict['key1'])

# Derive the first key for every dict
my_string = '\n'.join(e[list(e.keys()[0])] for e in my_dict['key1'])