[英]How to make a dictionary from another dictionary values
I have a list of dictionaries, something like this我有一个字典列表,像这样
input = [
{"0_question": "how are you"},
{"0_answer": "good"},
{"4_question": "what time is it"},
{"4_answer": "morning"},
]
and I want this:我想要这个:
expected_result = {
0: {"how are you": "good"},
4: {"what time is it" : "morning"},
}
this is what I tried:这是我尝试过的:
x = {}
l= []
for i, d in enumerate(a):
for k, v in d.items():
l.append(v)
x[l[i]] = l[i+1]
Split the original dict key
into numeric and type part:将原始dict key
拆分为数字和类型部分:
a = [
{
"0_question": "how are you"
}, {
"0_answer": "good"
}, {
"4_question": "what time is it"
}, {
"4_answer": "morning"
}
]
dic = {}
for item in a:
value = list(item.values())[0]
num, itemType = list(item.keys())[0].split('_')
num = int(num)
if itemType == 'question':
dic[num] = {value: ''}
else:
key = list(dic[num].keys())[0]
dic[num][key] = value
print(dic)
Out:出去:
{0: {'how are you': 'good'}, 4: {'what time is it': 'morning'}}
You can use a nested loop and the modulo operator ( %
).您可以使用嵌套循环和模运算符 ( %
)。 Use regex to find the question/answer number:使用正则表达式查找问题/答案编号:
import re
l = [
{"0_question": "how are you"},
{"0_answer": "good"},
{"4_question": "what time is it"},
{"4_answer": "morning"},
{"157_question": "which fruit do you want"},
{"157_answer": "apple"}
]
new_d = {}
for i, d in enumerate(l):
for k, v in d.items():
result = re.search("\d+", k).group(0)
num = int(result)
if ((i + 1) % 2) == 0:
for new_k in new_d[num].keys():
new_d[num][new_k] = v
else:
new_d[num] = {v: ""}
print(new_d)
Output Output
{0: {'how are you': 'good'}, 4: {'what time is it': 'morning'}, 157: {'which fruit do you want': 'apple'}}
Use This Code使用此代码
a = [{"0_question": "how are you"},
{"0_answer": "good"},
{"4_question": "what time is it"},
{"4_answer": "morning"}]
dic = {}
for i in range(len(a) - 1):
if i % 2 == 0:
dic[list(a[i].keys())[0]] = {list(a[i].values())[0]: list(a[i + 1].values())[0]}
print(dic)
This has fewer lines and hopefully increases readability.这有更少的行,并有望提高可读性。 The downside is it uses more resources by restructuring the initial data.缺点是它通过重组初始数据使用更多资源。
sample_data = [{"0_question" : "how are you"},
{"0_answer": "good"},
{"4_question" : "what time is it"},
{"4_answer": "morning"}]
restructured_data = {k: v for data in sample_data for k, v in data.items()}
nums = list(set([int(k.split("_")[0]) for k, v in restructured_data.items()]))
new_dict = {num: {restructured_data[f'{num}_question']: restructured_data[f'{num}_answer']} for num in nums}
print(new_dict)
output: output:
{0: {'how are you': 'good'}, 4: {'what time is it': 'morning'}}
data = [{"0_question" : "how are you"},
{"0_answer": "good"},
{"4_question" : "what time is it"},
{"4_answer": "morning"}]
# unpack dict values into any iterable data structure
# list in my case
unpacked_data = list(map(lambda dict_: list(dict_.items()), data))
# dict_items is not subscriptable, so unpack it again
# also exctracting number from key.
processed_data = list(
map(
lambda values_tuple: (values_tuple[0][0][0], values_tuple[0][1]),
unpacked_data
)
)
result_dict = {}
# according to input data we assuame that there is a pairs of (question: answer).
# using zip and slicing for pair iteration
for question, answer in zip(processed_data[0::2], processed_data[1::2]):
result_dict[question[0]] = {question[1] : answer[1]}
print(result_dict)
UPD: this may be not the most optimal solution, but i hope that is pretty clear for understanding UPD:这可能不是最佳解决方案,但我希望这很容易理解
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.