简体   繁体   中英

How to get value from dictionary in list of tuples?

I have a dictionary like below and I want to store the values meaning 1, 1 in a list.

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

I want an array [1,1,1] .

This is my code:

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 and t2 being respectively the first and second item of each tuple, and k , v the key-value pairs in the dict t2 .

You can use unpacking:

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

Output:

[1, 1, 1]

It can become slightly cleaner with one additional step:

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

You can use next to retrieve the first value of your dictionary as part of a list comprehension.

This works since your dictionaries have length 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]

I tried the simple way like below:

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

The output l would be [1, 1, 1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM