'Delete key and value form a dictionary, if it is longer than 5 symbols
How to create a new dictionary where all keys and values are converted to string type? If string length is more than 5 symbols it must be excluded from the answer (both the key and value)
My code now looks like this:
file1data = {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}
key_values = file1data.items()
new_dictionary = {str(key):str(value) for key, value in key_values}
print((str(new_dictionary)))
It can covert all values and keys to a string type, but not detect if length is more than 5.
For example if is given this dictionary: {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}
The result should be: {"1":"2","2":"5","1231":"14","-2":"7"}
Solution 1:[1]
A simple way to do it is to iterate through the keys of the dictionary and check if you should delete it or not if yes add it to a list and delete it later
file1data = {"1":"2",2:5,"12dade":-1,"1231":14,"-2":7}
delete = list()
for key in file1data:
if len(str(key)) > 5:
delete.append(key)
for i in delete:
del file1data[i]
I know that it is not the most compact way to do it but it works
Solution 2:[2]
Use a comprehension:
d = {'1': '2', 2: 5, '12dade': -1, '1231': 14, '-2': 7}
out = {k: v for k, v in d.items() if len(str(k)) <= 5 and len(str(v)) <= 5}
print(out)
# Output
{'1': '2', 2: 5, '1231': 14, '-2': 7}
Solution 3:[3]
Without converting to string twice:
{sk: sv
for k, v in file1data.items()
if len(sk := str(k)) <= 5
if len(sv := str(v)) <= 5}
Solution 4:[4]
You can achieve this by using an if clause inside of the dictionary comprehension, like so:
file_data = {"1": "2", 2: 5, "12dade": -1, "1231": 14, "-2": 7}
filtered_file_data = {str(key): str(value) for key, value in file_data.items() if len(str(key)) <= 5 and len(str(value)) <= 5}
print(filtered_file_data)
Output:
{'1': '2', '2': '5', '1231': '14', '-2': '7'}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mario Khoury |
| Solution 2 | |
| Solution 3 | Kelly Bundy |
| Solution 4 | Kelly Bundy |
