Home > OS >  i'm trying to get a value in a dictionary should be a list
i'm trying to get a value in a dictionary should be a list

Time:09-28

list_of_dict =      
    [{'f_text': 'sample', 'symbol': '*', 'f_id': 246, 'record_id': ['4680', '4679'], 'flag': 'N'}, 
     {'f_text': 'other text', 'symbol': '!#', 'f_id': 247, 'record_id': 4678, 'flag': 'N'}]

in the above dictionary some of the record_id are in list and some are in string. I'm trying to convert all the values of record_id to list.

expected output:

list_of_dict =     
    [{'f_text': 'sample', 'symbol': '*', 'f_id': 246, 'record_id': ['4680', '4679'], 'flag': 'N'}, 
     {'f_text': 'other text', 'symbol': '!#', 'f_id': 247, 'record_id': ['4678'], 'flag': 'N'}]

please guide me with the solution

CodePudding user response:

This is another approach for the same:

from copy import copy
list_of_dict=[{'f_text':'sample', 'symbol':'*', 'f_id':246, 'record_id':'4679', 'flag': 'N'},
{'f_text':'sample', 'symbol':'*', 'f_id':246, 'record_id':'4680', 'flag': 'N'},
{'f_text':'other text', 'symbol':'!#', 'f_id':247, 'record_id':'4678', 'flag': 'N'},
{'f_text':'other text', 'symbol':'!#', 'f_id':248, 'record_id':'4678', 'flag': 'N'},
{'f_text':'other text', 'symbol':'!#', 'f_id':247, 'record_id':'4677', 'flag': 'N'},]
visited_fids = {}
cnt = 0
list1 = list_of_dict.copy()
for index, data in enumerate(list1):
    if (data['f_id'] in visited_fids):
        list_of_dict[visited_fids[data['f_id']]]['record_id'].append(data['record_id'])
        list_of_dict.remove(data)
    else:
        data['record_id'] = [data['record_id']]
        visited_fids[data['f_id']] = cnt
        cnt =1
        
print (list_of_dict)

Output:

[{'f_text': 'sample', 'symbol': '*', 'f_id': 246, 'record_id': ['4679', '4680'], 'flag': 'N'}, {'f_text': 'other text', 'symbol': '!#', 'f_id': 247, 'record_id': ['4678', '4677'], 'flag': 'N'}, {'f_text': 'other text', 'symbol': '!#', 'f_id': 248, 'record_id': ['4678'], 'flag': 'N'}]

CodePudding user response:

You need dictionary unpacking with two stars, not just one:

result = [{**l[0], 'record_id': list(set([x['record_id'] for x in l]))} for _, v in groupby(sorted(list_of_dict, key=lambda x: x['f_id']), key=lambda x: x['f_id']) if len(l:=list(v))]

Output:

>>> result
[{'f_text': 'sample', 'symbol': '*', 'f_id': 246, 'record_id': ['4680', '4679'], 'flag': 'N'}, 
 {'f_text': 'other text', 'symbol': '!#', 'f_id': 247, 'record_id': ['4678'], 'flag': 'N'}]
>>> 
  • Related