Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading