Home > OS >  changes the type of values in list of dictionaries
changes the type of values in list of dictionaries

Time:09-28

In the dictionary below some of the record_id are in list and some are in integer. I'm trying to convert all the values of record_id to list of strings.

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

I've tried below code:

for each in result:
    record_value = each['record_id']
    record_value = str(record_value)
    print(type(record_value))
    if type(record_value)1= list:
        record_value = record_value.split()
        each['record_id'] = record_value

expected output:

list_of_dict =      
    [{'f_text': 'sample', 'symbol': '*', 'f_id': 246, 'record_id': ['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:

You can use a list/dictionary comprehension and a type check with isinstance:

[{k: list(map(str, v)) if isinstance(v, list) else v
  for k,v in d.items()}
  for d in list_of_dict]

output:

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

edit here is an alternative to ensure that the "record_id" are lists of strings

[{k: (list(map(str, v)) if isinstance(v, list) else [str(v)]) if k == 'record_id' else v
  for k,v in d.items()}
 for d in list_of_dict]

output:

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

CodePudding user response:

Try this: (If map(str, ld['record_id']) got error and ld['record_id'] have one number we go to except)

for ld in list_of_dict:
    try:
        ld['record_id'] = list(map(str, ld['record_id']))
    except TypeError:
        ld['record_id'] = [str(ld['record_id'])]

Output:

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

If you want to change only type of number in list you can try this:

for ld in list_of_dict:
    try:
        ld['record_id'] = list(map(str, ld['record_id']))
    except TypeError:
        continue

Output:

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