Reputation: 143
I have the following dictionary within a list as I understand:
[{'week': 3, 'timing': '07:30'}, {'week': 4, 'timing': '20:30'},{},....]
I would like to extract timing and week and have them on separate lists. However, as there is a list on the outside there are no keys recognized. What I tried to do is the following:
for item in list:
new_list =list( item.values() )[0]
But it shows an error because some of them are blank I think. Currently, I get the error: IndexError: list index out of range. How can I extract them to two separate lists and have a NaN where they are blank?
Upvotes: 0
Views: 78
Reputation: 439
I used this code to extract them separately.
weeks = [ a['week'] for a in new_list ]
timings = [ a['timing'] for a in new_list ]
Upvotes: 0
Reputation: 18367
You start by creating two lists and append the items. The iteration should be done over each object in the list, each object is the dictionary itself. Let's say the list that contains dictionaries is called full_list
, because naming it list
wouldn't be too convenient for python.
week_list = []
timing_list = []
for i in full_list:
week_list.append(i['week'])
timing_list.append(i['timing'])
If there are dictionaries with empty values, or empty dictionaries, or dictionaries with only week
but no timing
for example, I like to use:
import numpy as np
for i in full_list:
try:
week_list.append(i['week'])
except KeyError:
week_list.append(np.nan)
try:
timing_list.append(i['timing'])
except KeyError:
timing_list.append(np.nan)
This way you'll append a NaN
value to your list whenever the key doesn't exist and that will prove helpful if you are later performing operations with the lists.
Full example:
full_list = [{'week': 3, 'timing': '07:30'}, {'week': 4, 'timing': '20:30'},{},{'week':4},{'timing':'09:21'},{}]
week_list = []
timing_list = []
import numpy as np
for i in full_list:
try:
week_list.append(i['week'])
except KeyError:
week_list.append(np.nan)
try:
timing_list.append(i['timing'])
except KeyError:
timing_list.append(np.nan)
print(week_list)
print(timing_list)
Output:
[3, 4, nan, 4, nan, nan]
['07:30', '20:30', nan, nan, '09:21', nan]
If the dictionary was like the following:
full_dict = {'person_1':{'week': 3, 'timing': '07:30'},'person_2':{'week': 4, 'timing': '20:30'},'person_3':{}}
The iteration should be done per each key
. Therefore the loop would be:
for i in full_dict.keys():
and exactly the same code as before
Upvotes: 1
Reputation: 504
The following code will help to extract the week and time value separately
check = [{'week': 3, 'timing': '07:30'}, {'week': 4, 'timing': '20:30'}]
week_list = []
timing_list=[]
for i in check:
for k,v in i.items():
if k == 'week':
week_list.append(v)
else:
timing_list.append(v)
Output
```[3, 4]
['07:30', '20:30']
Upvotes: 3