简体   繁体   中英

How do I delete keys from a dictionary that are shorter than a certain length in python?

I have a dictionary that has keys of different word lengths, for example:

d={'longggg':'a', 'short':'b', 'medium':'c', 'shor':'d'}

and I want to end up with a dictionary that only has keys that are greater than a certain length. For example, I want to only keep entries that are 6 letters long or more. So I want

new_d={'longggg':'a', 'medium':'c'}.

I tried

new_d=dict(k,v) for k,v in d.items() if len[k]>=6

and

new_d={}
for k, v in d.items():
    if len[k]>=6:
        new_d.update({k:v})

along with many other variations of that code, but the problem ends up being in taking the length of a key.

Use Dictionary comprehensions . No need to do for k in d.keys() . Just use for k in d as d.keys() will return a list which is not needed at all. (A lesson I learnt from Stackoverflow itself!!)

Also as @roganjosh pointed out use len() instead of len[] ( len() is a function). Square brackets are used for indexing in say, lists and strings.

d={'longggg':'a', 'short':'b', 'medium':'c', 'shor':'d'}

a = {k:d[k] for k in d if len(k)>=6}
print a

Output:

{'medium': 'c', 'longggg': 'a'}

You can try this:

d={'longggg':'a', 'short':'b', 'medium':'c', 'shor':'d'}
final_d = {a:b for a, b in d.items() if len(a) >= 6}

Output:

{'medium': 'c', 'longggg': 'a'}

len is a built-in function in Python, and therefore uses parentheses (not the square brackets operator).

The big issue (among other things) with your first solution is that you are creating a separate dictionary for each k, v .

Your second solution should work if you fix the len function call, but I would rewrite new_d.update({k:v}) as new_d[k] = v , since that's the standard way to use a Python dictionary.

I can tell you're new, and the best resource for beginner's questions like these will be the Python documentation rather than Stack Overflow. You should also try copy and pasting your error output into Google. You'll probably be able to solve your problems quicker and you'll get more meaningful answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM