sara jones
sara jones

Reputation: 145

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)

Upvotes: 3

Views: 75

Answers (4)

lola
lola

Reputation: 115

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]

Upvotes: 0

jpp
jpp

Reputation: 164843

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]

Upvotes: 0

fferri
fferri

Reputation: 18950

>>> [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.

Upvotes: 3

Ajax1234
Ajax1234

Reputation: 71471

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]

Upvotes: 1

Related Questions