How to remove words from list of values in specific dictionary key?

Related searches

I need to remove a list of words from the values of a specific key in my list of dictionaries.

Here is an example of how my data looks like:

words = ['cloves', 'packed']

data = [{'title': 'Simple Enchiladas Verdes',
         'prep_time': '15 min',
         'cook_time': '30 min',
         'ingredients': ['chicken breast', 'tomato sauce', 'garlic cloves', 'fresh packed cilantro']
         'instructions': ['some text...'],
         'category': 'dessert',
         'cuisine': 'thai', 
         'article': ['some text...']
        },
        {...}, {...}]

Desired output:

data = [{'title': 'Simple Enchiladas Verdes',
         'prep_time': '15 min',
         'cook_time': '30 min',
         'ingredients': ['chicken breast', 'tomato sauce', 'garlic', 'fresh cilantro']
        },
        {...}, {...}]

I have tried different codes:

remove = '|'.join(words)
regex = re.compile(r'\b('+remove+r')\b', flags=re.IGNORECASE)

for dct in data:
    dct['ingredients']= list(filter(lambda x: regex.sub('', x), dct['ingredients']))

But this return the following error : TypeError: sub() missing 1 required positional argument: 'string'

Other codes I tried:

for dct in data:
    dct['ingredients']= list(filter(lambda x: x != words, dct['ingredients']))
for dct in data:
    dct['ingredients']=[[el for el in string if el in words ] for string in dct['ingredients']]
for dct in data:
    for string in dct['ingredients']:
        dct['ingredients'] = list(filter(lambda x: x not in words, dct['ingredients']))

But none of them resolve my problem.

Why not a list comprehension with a dictionary comprehension:

data = [{k:([' '.join([s for s in x.split() if s not in words]) for x in v] if k == 'ingredients' else v) for k, v in i.items()} for i in data]

If a dictionary key contains a certain word, how would I remove it , Why not use a dict comprehension instead of doing it inplace ? Replacing the name of the key in a dict , you can easily do that by using dict� The following code example shows how to remove a key/value pair from a dictionary using the Remove method. This code example is part of a larger example provided for the Dictionary<TKey,TValue> class (openWith is the name of the Dictionary used in this example). // Use the Remove method to remove a key/value pair.

In your re.sub appraoch, you should use map, not filter (you are not filtering out individual words, but replacing the whole string with the result of re.sub)

for dct in data:
    dct['ingredients']= list(map(lambda x: regex.sub('', x), dct['ingredients']))

Or, probably more readable, as a list comprehension:

    dct['ingredients'] = [regex.sub("", x) for x in dct['ingredients']]

Both will leave some excess spaces, though. If words are always separated with a space, you can just use split and join (faster if words is a set):

for dct in data:
    dct['ingredients'] = [' '.join(w for w in string.split() if w not in words)
                          for string in dct['ingredients']]

Python - Remove Dictionary Key Words, Python – Remove Dictionary Key Words Let's discuss certain ways in which this task can be performed. In this, we perform the task of converting string to list of words using split(). Remove duplicate values across Dictionary Values � Python - Append Dictionary Keys and Values ( In order ) in dictionary� Python Exercises, Practice and Solution: Write a Python program to remove duplicates from Dictionary.

words = ['cloves', 'packed']

data = [{'title': 'Simple Enchiladas Verdes',
         'prep_time': '15 min',
         'cook_time': '30 min',
         'ingredients': ['chicken breast', 'tomato sauce', 'garlic cloves', 'fresh packed cilantro']}
        ]
for i in data:
    word = ' @! '.join(i['ingredients'])
    for k in words:
        word = word.replace(k,'').strip()

    i['ingredients']=[i.strip() for i in word.split('@!')]

output

[{'title': 'Simple Enchiladas Verdes',
  'prep_time': '15 min',
  'cook_time': '30 min',
  'ingredients': ['chicken breast',
   'tomato sauce',
   'garlic',
   'fresh  cilantro']}]

Python, Python | Removing dictionary from list of dictionaries The common utility to remove the dictionary corresponding to particular key in a list of to the introduction of No-SQL databases, which work mostly on Key-Value pairs. A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

words = ['cloves', 'packed']

data = [{'title': 'Simple Enchiladas Verdes',
         'prep_time': '15 min',
         'cook_time': '30 min',
         'ingredients': ['chicken breast', 'tomato sauce', 'garlic cloves', 'fresh packed cilantro']
        },
        {'title': 'Simple Enchiladas Verdes11',
         'prep_time': '15 min11',
         'cook_time': '30 min11',
         'ingredients': ['chicken breast1', '1tomato sauce', '1garlic cloves', '1fresh packed cilantro']}
        ]

n = []
for d in data:
    for item in d['ingredients']:
        for word in words:
            item = item.replace(word, '')
        n.append(item)
    d['ingredients'] = n

print (d)

output:

{'title': 'Simple Enchiladas Verdes11', 'prep_time': '15 min11', 'cook_time': '30 min11', 'ingredients': ['chicken breast', 'tomato sauce', 'garlic ', 'fresh  cilantro', 'chicken breast1', '1tomato sauce', '1garlic ', '1fresh  cilantro']}

remove a key value from dictionary python Code Example, Get code examples like "remove a key value from dictionary python" instantly right from your google search results with the Grepper Chrome Extension. Sometimes, we may require a way in which we have to get all the values of specific key from a list of dictionary. This kind of problem has a lot of application in web development domain in which we sometimes have a json and require just to get single column from records.

Ch.6: Dictionaries and strings, (= "lists with text index"); Dictionary in Python is called hash, HashMap and Can test for particular keys, delete elements, etc Delete an element of a dict: split it into words; initialize a dictionary with the property names as keys and empty� You can remove the first item from the list where its value is equal to the specified value with remove (). l = ['Alice', 'Bob', 'Charlie', 'Bob', 'Dave'] print(l) # ['Alice', 'Bob', 'Charlie', 'Bob', 'Dave'] l.remove('Alice') print(l) # ['Bob', 'Charlie', 'Bob', 'Dave']

You can convert Python dictionary keys/values to lowercase by simply iterating over them and creating a new dict from the keys and values. For example,def lower

Get all the Values in a Dictionary. Remove a key from Dictionary. Add key/value pairs in Dictionary. Find keys by value in Dictionary. Filter a dictionary by conditions. Print dictionary line by line. Convert a list to dictionary. Sort a Dictionary by key. Sort a dictionary by value in descending or ascending order. Dictionary: Shallow vs Deep Copy

Comments
  • Great answer. +1
  • But that would replace the words in all my keys and not only in the key['ingredients'], right?
  • @annag Actually, why? tha's the only one that could be replaced, since iterating trough strings will give one character, and list values are more
  • @U9-Forward because I have other keys in the dictionary (not displayed here). I will modify the data example.
  • @annag Edited my answer, please accept it if it works :-)