Home > Back-end >  How to modify dict elements based on key value?
How to modify dict elements based on key value?

Time:08-10

I struggle with some basic idea (I guess)


list_a = [{'title': 'some product name ()', 'network': 'network_one'}, {'title': 'another product name - some more', 'network': 'network_two'}]

keys_dict = {
    'network_one': items['title'].split('(')[0].title().rstrip(), #yup - I know its wrong but you have the idea
    'network_two': items['title'].split('-')[0].lower().rstrip(),
}

l = []
for items in list_a:
    # print(i)
    if items['network'] in keys_dict:
        items['product'] = keys_dict[items['network']]
        l.append(items)
print(l)

Given is a list_a;

I want o to create new key 'product' based on 'network' key values from list_a. So if the 'network' == 'network_one', 'product' value should be created by applying

split('(')[0].title().rstrip()

on 'title' value

Different 'title' string transformations based on another key value and creating new key, value from it.

Simple if,else does work here for me but when you have plenty of data; I guess it's easier to manage when you use dicts.

Expected output =

l = [{'title': 'some product name ()', 'network': 'network_one', 'product: 'Some product name'}, {'title': 'another product name - some more', 'network': 'network_two', 'product': 'another product name'}]

A simple strings as a new values like below does work but and I know how to handle them I have no idea of how to apply the above scenario where the key values have to (?) be strings modification values rstrip etc


keys_dict = {
    'network_one': 'product name', 
    'network_two': 'another product name',
}

CodePudding user response:

You can use a lambda function in your keys_dict that should take a string as argument and does the appropriate conversion.

keys_dict = {
    'network_one': lambda s: s.split('(')[0].title().rstrip(),
    'network_two': lambda s: s.split('-')[0].lower().rstrip(),
}

new_list = []
for d in list_a:
    if (network := d['network']) in keys_dict:
        d['product'] = keys_dict[network](d['title'])
        new_list.append(d)

CodePudding user response:

i would use re for this task:

from re import search

list_a = [{'title': 'some product name ()', 'network': 'network_one'}, 
          {'title': 'another product name - some more', 'network': 'network_two'}]

for d in list_a:
    d['product'] = search(r'^(.*) [(-]?',d['title'])[1]

>>> list_a
'''
[{'title': 'some product name ()',
  'network': 'network_one',
  'product': 'some product name'},
 {'title': 'another product name - some more',
  'network': 'network_two',
  'product': 'another product name'}]
  • Related