如何从元组列表中的字典中获取值?

2024-06-24 11:47:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像下面这样的字典,我想在一个列表中存储表示1,1的值。你知道吗

sc_dict=[('n', {'rh': 1}), ('n', {'rhe': 1}), ('nc', {'rhex': 1})]

我想要一个数组[1,1,1]。你知道吗

这是我的密码:

dict_part = [sc[1] for sc in sc_dict]

print(dict_part[1])

L1=[year for (title, year) in (sorted(dict_part.items(), key=lambda t: t[0]))]
print(L1)

Tags: inl1列表for字典数组yeardict
3条回答

可以使用next检索字典的第一个值,作为列表理解的一部分。你知道吗

因为你的字典长度是1。你知道吗

sc_dict=[('n', {'rh': 1}), ('n', {'rhe': 1}), ('nc', {'rhex': 1})]

res = [next(iter(i[1].values())) for i in sc_dict]

# [1, 1, 1]
>>> [v for t1, t2 in sc_dict for k, v in t2.items()]
[1, 1, 1]

t1t2分别是每个元组的第一项和第二项,kv是dictt2中的键值对。你知道吗

您可以使用解包:

sc_dict=[('n', {'rh': 1}), ('n', {'rhe': 1}), ('nc', {'rhex': 1})]
new_data = [list(b.values())[0] for _, b in sc_dict]

输出:

[1, 1, 1]

只需一个附加步骤,它就可以变得稍微干净一些:

d = [(a, b.items()) for a, b in sc_dict]
new_data = [i for _, [(c, i)] in d]

相关问题 更多 >