Home > Mobile >  Delete key and value form a dictionary, if it is longer than 5 symbols
Delete key and value form a dictionary, if it is longer than 5 symbols

Time:02-08

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"}

CodePudding user response:

Add if statement inside dict comprehension like so

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 if len(str(key)) <= 5 and len(str(value)) <= 5}

print((str(new_dictionary)))

CodePudding user response:

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

CodePudding user response:

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}
  •  Tags:  
  • Related