Deleting Dictionaries Keys with a For If Statement in Python 3 - python-3.x

I feel very dumb asking this. How do I delete a keys in a dictionary with an if statement that references the values. When I do this:
newdict = {"a":1,"b":2,"c":3}
for (key,value) in newdict:
if value == 2:
del newdict[key]
print(newdict)
It throws this error:
line 3, in <module>
for (key,value) in newdict:
ValueError: not enough values to unpack (expected 2, got 1)
Thank you.

If you need to delete based on the items value, use the items() method or it'll give ValueError. But remember if you do so it'll give a RuntimeError. This happens because newdict.items() returns an iterator not a list. So, Convert newdict.items() to a list and it should work. Change a bit of above code like following -
for key,value in list(newdict.items()):
if value == 2:
del newdict[key]
output -
{'a': 1, 'c': 3}

Related

Python navigating nested dictionary

I have a nested dictionary that might have non-unique keys
I need to dynamically add/get key-value pairs on this dictionary by their key in string format
The string that is the key name is being read from keyboard input in string format
Given that string I have to find a key that matches it and do something with a corresponding key-value pair
The keys might be non-unique among different nesting levels
But they are unique on a single nesting level
For example, I have this dict:
MyDict = {'a': 1, 'b': 2}
Now, I get some input in string format that tells me to add one more nesting level with key 'c' and then fill it with a key-value pair 'a:3'. I do it like that:
last_edited_element = {'a': 3}
MyDict['c'] = last_edited_element
#MyDict is now {'a': 1, 'b': 2, 'c': {'a': 3}}
Then, I get an input that tells me to do something with a key-value pair that has 'a' key
I am given a rule that first I have to look up for 'a' key in a level that was edited last, then If nothing is found - go one level up. I store my last edited element in a variable last_edited_element.
The last edited element was {'a': 3}, so I do:
if 'a' in last_edited_element:
#do something with {'a': 3}
else:
#go one level up and look for 'a' key there
So the question is, how do I go one level up? I have {a: '3'} stored in a variable last_edited_element, I need to access the upper-level dictionary if any that contains last_edited_element, something like last_edited_element.get_parent_dictionary()
How do I do that?
So following up on my first comment, you could do this:
Initialize a top-level dict
Initialize all children to refer to their parent
Recursively search bottom-up until you find a key or None
example_dict = {'a': 1, 'b': 2, 'parent': None}
example_dict['c'] = {'a': 3, 'parent': example_dict}
def find_key(k, d):
if k in d:
return d[k]
elif d['parent'] is None:
return None
return find_key(k, d['parent'])
print(find_key('a', example_dict['c']))
> 3
print(find_key('b', example_dict['c']))
> 2

can't remove some duplicate elements from a list in python

well I was trying to remove duplicate items from a list so it has unique items and I also wanted to use for and if my code went so well but in one condition I faced something I don't understand. this is the example :
a = [1,2,2,3,3,3,21,21,16,20,28,28,7]
for x in a:
if a.count(x) > 1:
for z in range(a.count(x)):
a.remove(x)
print(a)
[1, 21, 21, 16, 20, 7]
I don't understand why !! It removes 2,3,28 which was predicted but not 21 !
any help would be great , thanks.
The best solution for this case is using set(). If you do list(set(a)) it will remove all duplicates.
Notice that set() is not the same as list() so be sure to turn it back to a list if you want to keep using list methods.
About your code, the problem with your code is that you're running on the list as you're changing it.
While you run over the items the indexes changes and that's why you miss some of the items.
You can see more clearly what happens if you add a print to understand what's x's value:
a = [1,2,2,3,3,3,21,21,16,20,28,28,7]
for x in a:
print(x)
if a.count(x) > 1:
for z in range(a.count(x)):
a.remove(x)
I believe your issue is that you are changing the list while you're looping over it
Try using a.copy() to create a new copy of the list to loop over like so.
a = [1,2,2,3,3,3,21,21,16,20,28,28,7]
for x in a.copy():
if a.count(x) > 1:
for z in range(a.count(x)):
a.remove(x)
print(a)
This code will output
[1, 16, 20, 7]

variable in string of dictionary in python

I have the following dictionary in python 3:
a = {'a': 'b:{androidString}'}
Try to define a variable and use it in the dictionary:
android = "androidString"
a = {'a': f'b:{{android}}'}
when:
print(a)
it says:
{'a': 'b:{android}'}
how to use the variable in the dictionary?
You're missing a curly bracket :
a = {'a': f'b:{{{android}}}'}
Output
{'a': 'b:{androidString}'}
Just use get method:
...
a.get('a')
get method takes two parameters first key name , second default
default returns Errors in default but you can change it to False
so when you try to get key doesn't exists it will return default
or you can use []:
...
a['a']
there are a lot options to get key of dictionary More info

"TypeError: 'int' object is not subscriptable"

Why am i getting this error when trying to remove dupes from a list?
"TypeError: 'int' object is not subscriptable"
trying to remove duplicate valuse from a list
numbers=[5,2,1,7,2,4]
numbers.sort()
i=0
for item in numbers:
if i==len(numbers)-1:
break
elif item[i]==item[i+1]:
numbers.remove(item)
i+=1
Actually the problem is in your for loop it is not for removing duplicate numbers. i recommend that you must define a empty list in which you append elements one by one using loop and check if the element is already present in your list then don't append. here is the code:
numbers=[5,2,1,7,2,4]
numbers.sort()
sorted_num=[]
i=0
for i in range(0,len(numbers)-1):
if numbers[i] in sorted_num:
continue
else:
sorted_num.append(numbers[i])
i+=1
print (sorted_num)
# elif item[i]==item[i+1]:
# numbers.remove(item)
# i+=1
i only edited your piece of code
use set see more here
numbers=[5,2,1,7,2,4]
list(set(numbers))
[1, 2, 4, 5, 7]
Use dictionary:
numbers=[5,2,1,7,2,4,5,5,1]
numbers=list(dict.fromkeys(numbers))
print(numbers)

Returning a list of N dictionary keys that have the maximum integer values

my_dict = {'label': 6, 'label_2': 5, 'label_3': 9, 'label_4': 12}
I would like to create a list that will contain the top 2 (or 3, or 4, or 50... this will vary) dictionary keys, according to their highest values. So in the example above if I wanted the top 2, I should get:
['label_3', 'label_4']
for top 3 I should get:
['label', 'label_3', 'label_4']
And so on.
After reading some other stackoverflow threads, I've been experimenting with heapq, but can't get it to work the way I want. Would appreciate some help.
Of course, the moment I post here, I find a solution (thanks to the heapq documentation). This works:
my_list = heapq.nlargest(3, my_dict, key=my_dict.get)
This will go over my_dict and return the keys with the 3 largest values.
Thanks.

Resources