A snippet from my dictionary my_emotions
looks like this:
{'art': [(2135, ['anticipation', 'joy', 'sadness', 'surprise'])],
'bad': [(7542, ['anger', 'disgust', 'fear', 'sadness'])],
'beautiful': [(4000, ['joy']), (4425, ['joy'])],
'boy': [(777, ['disgust']), (2634, ['disgust']), (4442, ['disgust'])],
'ceremony': [(2948, ['joy', 'surprise'])],
'child': [(4263, ['anticipation', 'joy'])],
'detention': [(745, ['sadness']),
(3461, ['sadness']),
(3779, ['sadness']),
(4602, ['sadness'])],...]}
I am aiming to output all the first numbers of every tuple that occur in every key into a list.
So far I've tried this:
for key in sorted(my_emotions.keys()):
auto_emotion_indices = [].append(my_emotions[key][0][0])
but it outputs None
.
I tried printing the output to see what I'm getting, using:
for key in sorted(my_emotions.keys()):
auto_emotion_indices = [].append(my_emotions[key][0][0])
which outputs the part of the dictionary that I want (the numbers aka indices), but only the first ones when there's multiple occurances for a key.
Eg for the key detention
: I only get 745
, but not 3461
, 3779
etc...
A desired output would be:
my_list = [2135, 7542, 4000, 4425, 777, 2634, 4442, 2948, 4263, 745, 3461, 3779, 4602...]
What should I add to also include the rest of those numbers into my list?
Thanks in advance!
Defining my_emotions as:
my_emotions = {'art': [(2135, ['anticipation', 'joy', 'sadness', 'surprise'])],
'bad': [(7542, ['anger', 'disgust', 'fear', 'sadness'])],
'beautiful': [(4000, ['joy']), (4425, ['joy'])],
'boy': [(777, ['disgust']), (2634, ['disgust']), (4442, ['disgust'])],
'ceremony': [(2948, ['joy', 'surprise'])],
'child': [(4263, ['anticipation', 'joy'])],
'detention': [(745, ['sadness']),
(3461, ['sadness']),
(3779, ['sadness']),
(4602, ['sadness'])]}
This pythonic line will do the trick:
my_list = [number for emotion in sorted(my_emotions.keys()) for number, _ in my_emotions[emotion]]
A less pythonic way is to do it with two for loops:
my_list = []
for emotion in sorted(my_emotions.keys()):
for number, _ in my_emotions[emotion]:
my_list.append(number)
If you want to check what is being added just insert a print statement in the inner loop. In both cases the output is:
[2135, 7542, 4000, 4425, 777, 2634, 4442, 2948, 4263, 745, 3461, 3779, 4602]
auto_emotion_indices = []
for keys in sorted(my_emotions.keys()):
for item in my_emotions[keys]:
auto_emotion_indices.append(item[0])
print(auto_emotion_indices)
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.