Python list remove dict

5 ways to Remove duplicates list of Python dictionaries

In this post, we will understand the different 5 ways to Remove duplicates list of Python dictionaries with examples. Here we are using simple for loop, list comprehension,frozenset(), and many more techniques.

1. For loop to Remove duplicates list of Python dictionaries

The simple and easy method comes to our mind to loop over lists of dictionaries and compares the value for a duplicate to remove the duplicate value.

In this code example, we are looping over the lists of dictionaries and removing the duplicate dictionary, and appending it in the new dictionary.

Let us understand with code examples and build our understanding from it.

Program Example

#Program to remove duplicates from a list of dictionaries Langlist = [, , <"C++" : 3>, , ,] #removing the duplicate entry unique_dict = [k for j, k in enumerate(Langlist) if k not in Langlist[j + 1:]] print('after Removing duplicate from list of dictionary =\n',unique_dict)

Output

after Removing duplicate from list of dictionary = [, <'C++': 3>, , ]

3. Remove duplicate lists of dictionary by convert list to tuple

In this code example, we are converting lists of dictionaries into a list of tuples, and further using the set Comprehension to remove the duplicate from the lists of dictionaries.

Let us understand with code examples and build our understanding.

Program Example

#Program to remove duplicates from a list of dictionaries Langlist = [, , <"C++" : 3>, , ,] #removing the duplicate entry unique_dict = [dict(tuple) for tuple in ] print('after Removing duplicate from list of dictionary =\n',unique_dict)

Output

after Removing duplicate from list f dictionary = [, , , <'C++': 3>]

4. Using package iteration_utilities.unique_everseen

In this code example, we are using the third-party package to remove duplicates from lists of dictionaries. We are importing the package iteration_utilities import unique_everseen and using its unique_everseen() function to remove duplicates.

Let us understand with code example below.

Program Example

#Program to remove duplicates from a list of dictionaries from iteration_utilities import unique_everseen Langlist = [, , <"C++" : 3>, , ,] #removing the duplicate entry unique_dict=list(unique_everseen(Langlist)) print('after Removing duplicate from list of dictionary =\n',unique_dict)

Output

after Removing duplicate from list of dictionary = [, , <'C++': 3>, ]

5. frozenset() to Remove duplicates list of dictionaries

frozenset() is an inbuilt function of python it takes iterable as an argument and makes it immutable(unchangeable) or it freezes the iterable object and makes it unchangeable. It returns an immutable frozenset() object initialize with the elements from the iterable.

In this code snippet, we are using the frozenset() to remove duplicates from lists of dictionaries.

Let us understand with the code example below.

Program Example

#Program to remove duplicates from a list of dictionaries Langlist = [, , <"C++" : 3>, , ,] #removing the duplicate entry unique_dict = .values() print("after Removing duplicate from list of dictionary ="+str(unique_dict))

Output

after Removing duplicate from list of dictionary = dict_values([, , <'C++': 3>, ])

Conclusion

In this post, we understood the different ways to remove duplicates from the list of dictionaries. We hope you will find these ways useful and these will help you to solve your problem.

These techniques will be really helpful when you are working on the Data analysis work and they help you clean your data set samples.

Источник

Ways to Delete a Dictionary in Python

Python Delete Dictionary

Want to delete a dictionary in Python? The Python Dictionary is a data structure used in Python that accepts elements in key-value pair form. In this article, we will be understanding different Ways of deleting a key-value pair from a Python Dictionary.

The dict.clear() to delete a dictionary in Python

Python has in-built clear() method to delete a dictionary in Python. The clear() method deletes all the key-value pairs present in the dict and returns an empty dict.

inp_dict = print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) inp_dict.clear() print("\nElements of the dict after performing the deletion operation:") print(str(inp_dict))
Elements of the dict before performing the deletion operation: Elements of the dict after performing the deletion operation: <>

Techniques to delete a key-value pair from a Python Dictionary

The following techniques can be used to delete a key-value pair from a dictionary:

  • Python pop() function
  • Python del keyword
  • In-built Python popitem() method
  • Dictionary Comprehension along with Python items() method

1. Using pop() method

Python pop() method can be used to delete a key and a value associated with it i.e. a key-value pair from a dictionary.

The pop() method basically accepts a key to be deleted from the dictionary. It deletes the key as well as the value associated with the key from the dict and returns the updated dict.

inp_dict = print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) pop_item = inp_dict.pop("A") print("\nThe deleted element:") print(str(pop_item)) print("\nElements of the dict after performing the deletion operation:\n") print(str(inp_dict))

In the above snippet of code, we have passed the key – “A” as an argument to the pop() method. Thus, it deletes the key value pair associated with “A”.

Elements of the dict before performing the deletion operation: The deleted element: Python Elements of the dict after performing the deletion operation: ​

2. Python del keyword

Python del is actually a keyword which is basically used for the deletion of objects. As we all are aware that Python considers everything as an object, that is why we can easily use del to delete a dictionary in Python by deleting elements individually.

Python del keyword can also be used to delete a key-value pair from the input dictionary values.

inp_dict = print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) del inp_dict["D"] print("\nElements of the dict after performing the deletion operation:\n") print(str(inp_dict))

Elements of the dict before performing the deletion operation: Elements of the dict after performing the deletion operation:

Example 2: Deleting a key-value pair from a Nested Dictionary

It is possible for us to delete the key-value pair from a nested Python Dictionary. The del keyword serves the purpose with the below syntax:

del dict[outer-dict-key-name]Python list remove dict
inp_dict = , "1":"Java","2":"Fortan"> print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) del inp_dict["Python"]["C"] print("\nElements of the dict after performing the deletion operation:\n") print(str(inp_dict))

Thus, here, we delete the key-value pair “ C:Tuple ” associated with the outer key “ Python “.

Elements of the dict before performing the deletion operation: , '1': 'Java', '2': 'Fortan'> Elements of the dict after performing the deletion operation: , '1': 'Java', '2': 'Fortan'>

3. Python popitem() method

Python popitem() function can be used to delete a random or an arbitrary key-value pair from a Python dict. The popitem() function accepts no arguments and returns the deleted key-value pair from the dictionary.

inp_dict = print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) pop_item = inp_dict.popitem() print("\nThe deleted element:") print(str(pop_item)) print("\nElements of the dict after performing the deletion operation:\n") print(str(inp_dict))

Elements of the dict before performing the deletion operation: The deleted element: (‘D’, ‘Javascript’) Elements of the dict after performing the deletion operation:

4. Python Dict Comprehension along with items() method

Python items() method along with Dict Comprehension can be used to delete a dictionary in Python.

Python items() method basically takes no arguments and returns an object containing a list of all the key-value pairs in the particular dictionary.

Python Dict Comprehension can be used to create a dictionary by accepting the key-value pairs from a particular iterable.

In the context of the deletion of key-value pairs from a dictionary, the items() method can be used to provide the list of key-value pairs to the dict comprehension as an iterable.

The if statement is used to encounter key-value mentioned ahead of it. If the mentioned key value is encountered, it returns a new dict containing all the key-value pairs excluding the key-value pair associated with the key to be deleted.

inp_dict = print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) res_dict = print("\nElements of the dict after performing the deletion operation:\n") print(str(res_dict))

Elements of the dict before performing the deletion operation: Elements of the dict after performing the deletion operation:

Delete a Dictionary in Python By Specifying Elements While Iteration

While dealing with Python Dictionary, we may come across situations wherein we would want a key-value pair to be deleted during the iteration of the dictionary.

To serve the purpose, we can create a list of the input-dictionary and use a for loop to traverse through the list of the dictionary.

Finally, by using an if statement , we would check for the loop to encounter the key to be deleted. As soon as the key is encountered, del keyword can be used to delete the key-value pair.

inp_dict = print("Elements of the dict before performing the deletion operation:\n") print(str(inp_dict)) for KEY in list(inp_dict): if KEY =="B": del inp_dict[KEY] print("\nElements of the dict after performing the deletion operation:\n") print(str(inp_dict))

Elements of the dict before performing the deletion operation: Elements of the dict after performing the deletion operation:

Conclusion

Thus, we have unveiled the different techniques to delete a key-value pair from Python Dictionary.

References

Источник

Removing key/value pairs in list of dicts

I have a list of dicts that all have the same keys. If a key’s value is None in all dicts then I want to remove them (A solution that creates a new dict is fine as well). I’m concerned about my Big O complexity of 2n 2 (correct me if I’m wrong). Are there better solutions to what I have below?

dicts = [, , ] expected = [, , ] keys = dicts[0].keys() keep_keys = [] for key in keys: vals = [] for d in dicts: if dPython list remove dict is not None: vals.append(dPython list remove dict) if len(vals) != 0: keep_keys.append(key) for d in dicts: for k in d.keys(): if k not in keep_keys: del d[k] print dicts == expected 

1 Answer 1

Any solution will have to read the values associated to each key of each dictionary; so you won’t be able to drop under \$\mathcal(n\times<>m)\$ where \$m\$ is the length of each dictionary. This is pretty much what you are doing, but the if k not in keep_keys call slows things a bit as it is \$\mathcal(m)\$ when it could be \$\mathcal(1)\$ by using a set or a dictionary.

If you change the keep_keys list into a set you simplify the logic a bit: as soon as you find a key whose value is not None you can add it into the set.

dicts = [, , ] expected = [, , ] keep_keys = set() for d in dicts: for key, value in d.items(): if value is not None: keep_keys.add(key) remove_keys = set(d) - keep_keys for d in dicts: for k in remove_keys: del d[k] print dicts == expected 

This code, as your original one, assume that there is at least one item in dicts ; otherwise set(d) will generate an exception as the variable d is not defined yet.

But this code mixes the actual logic with some tests. You should wrap it in a function to ease reusability and put the testing code under an if __name__ == ‘__main__’: clause:

def filter_nones(dictionaries): if not dictionaries: return keep_keys = set() for dict_ in dictionaries: for key, value in dict_.iteritems(): if value is not None: keep_keys.add(key) remove_keys = set(dict_) - keep_keys for dict_ in dictionaries: for key in remove_keys: del dict_Python list remove dict if __name__ == '__main__': dicts = [ , , , ] expected = [ , , , ] filter_nones(dicts) print dicts == expected 

Источник

Читайте также:  Angular typescript controller as
Оцените статью