[英]How to get value from dictionary in list of tuples?
我有一个像下面的字典,我想在列表中存储值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)
>>> [v for t1, t2 in sc_dict for k, v in t2.items()]
[1, 1, 1]
t1
和t2
分别是每个元组的第一和第二项,并且k
, v
是dict t2
中的键值对。
你可以使用拆包:
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]
您可以使用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]
我尝试了如下的简单方法:
sc_dict=[('n', {'rh': 1}), ('n', {'rhe': 1}), ('nc', {'rhex': 1})]
l = []
for i in range(len(sc_dict)):
l.extend(sc_dict[i][1].values())
print l
输出l
将是[1, 1, 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.