Reputation: 664
I have a nested list inside a nested dictionary. Those are lists when they have more than 1 value. I would like to only keep the first item of the list, and transform it into a single string.
Current list of dicts:
list_dicts= [{'id': ['data1', 'data2', 'data3'],'text': 'hello1'},
{'id': 'data20', 'text': 'hello2'}]
As you can see some 'id'
values are lists, but I would like to transform the list into what the second item of list_dicts
looks like.
Desired output:
list_dicts2= [{'id': 'data1','text': 'hello1'},
{'id': 'data20', 'text': 'hello2'}]
My code attempt:
for d in list_dicts:
for v in d['id']:
if v>0: #does not work becomes some 'v' are a single string, not a list
# v.pop() ..???
Upvotes: 1
Views: 65
Reputation: 145
i_l = [{'id': ['data1', 'data2', 'data3'],'text': 'hello1'},
{'id': 'data20', 'text': 'hello2'}]
o_l = []
for i in i_l:
d = {}
for k, v in i.items():
if isinstance(v, list):
d[k] = v[0]
else:
d[k] = v
o_l.append(d)
o_l
Upvotes: 1
Reputation: 1279
To save keep only the first element in case of lists as id
values, you can do:
list_dicts= [{'id': ['data1', 'data2', 'data3'],'text': 'hello1'},
{'id': 'data20', 'text': 'hello2'}]
for d in list_dicts:
if isinstance(d['id'], list):
d['id'] = d['id'][0]
print(list_dicts)
The output will be:
[{'id': 'data1', 'text': 'hello1'}, {'id': 'data20', 'text': 'hello2'}]
Upvotes: 1
Reputation: 211
You can do assignment instead of "pop"
for d in list_dicts:
if isinstance(d['id'], list):
d['id'] = d['id'][0]
Upvotes: 1
Reputation: 5745
Try those comprehensions:
list_dicts = [{k:(v[0] if isinstance( v, list ) else v) for k,v in dict_item.items() } for dict_item in list_dicts]
Note that it would do so to any key values pairs that have list..
Upvotes: 1