Python move (pop) single dictionary item into new dictionary [duplicate] - python

This question already has answers here:
Access an arbitrary element in a dictionary in Python
(14 answers)
Closed 3 years ago.
I have a dictionary and don't know the keys or values. I want to remove a single element (doesn't matter which) and create a new dictionary containing only that key and value, removing it from the old dictionary in the process.
dict(n items) -> newdict(1 item) and dict(n-1 items)
What I've tried:
newdict=dict.pop() - Would work perfectly for a list, but for dictionary it 1. requires a key and only returns a value, not a new dictionary or a key, value pair
newdict={dict.items()[0]} - TypeError: 'dict_items' object is not subscriptable
newdict={dict.keys()[0],dict.pop(dict.keys()[0])} - TypeError: 'dict_keys' object is not subscriptable
key=list(dict)[0] newdict={key,dict.pop(key)} - Works (finally), but isn't their a better way than converting the entire dictionary to a list just to grab one key?
Is there a more efficient way to move a single dictionary element into a new dictionary?
Edit: Having the single element as a tuple would also work. I just need both the key and value of the element I remove.

I think this is a good use-case for dict.popitem:
old_dict = {1: 2, 3: 4, 5: 6}
new_dict = {7: 8}
def move_item(old, new):
k, v = old.popitem()
new[k] = v
move_item(old_dict, new_dict)
print(old_dict, new_dict)
with result
{1: 2, 3: 4} {7: 8, 5: 6}

You can iterate
for key, value in dict.items():
if value == bla:
dict.pop(key)

Try:
for key, value in old_dict:
new_dict[key] = old_dict.pop(key)
# operate with new_dict

Related

Convert a list with duplicating keys into a dictionary and sum the values for each duplicating key

I am new to Python so I do apologize that my first question might not be asked clearly to achieve the right answer.
I thought if I converted a list with duplicating keys into a dictionary then I would be able to sum the values of each duplicating key. I have tried to search on Google and Stack Overflow but I actually still can't solve this problem.
Can anybody help, please? Thank you very much in advance and I truly appreciate your help.
list1 = ["a:2", "b:5", "c:7", "a:8", "b:12"]
My expected output is:
dict = {a: 10, b: 17, c: 7}
You can try this code:
list1 = ["a:2", "b:5", "c:7", "a:8", "b:12"]
l1 = [each.split(":") for each in list1]
d1 = {}
for each in l1:
if each[0] not in d1:
d1[each[0]] = int(each[1])
else:
d1[each[0]] += int(each[1])
d1
Output: {'a': 10, 'b': 17, 'c': 7}
Explanation:
Step 1. Convert your given list to key-value pair by splitting each of the elements in your original list from : and store that in a list/tuple
Step 2. Initialize an empty dictionary
Step 3. Iterate through each key-value pair in the newly created list/tuple and store that in a dictionary. If the key doesn't exist, then add new key-value pair to dictionary or else just add the values to it's corresponding key.
A list does not have "keys" per say, rather it has elements. In your example, the elements them selves are a key value pair. To make the dictionary you want you have to do 3 things,
Parse each element into its key value pair
Handle duplicate values
Add each pair to the dictionary.
the code should look like this
list1 = ["a:2", "b:5", "c:7", "a:8", "b:12"]
dict1={}#make an empty dictionary
for element in list1:
key,value=element.split(':')#This splits your list elements into a tuple of (key,value)
if key in dict1:#check if the key is in the dictionary
dict1[key]+=int(value)#add to existing key
else:
dict1[key]=int(value)#initilize new key
print(dict1)
That code prints out
{'a': 10, 'c': 7, 'b': 17}
You could use a defaultdict, iterate over each string and add the corresponding value after splitting it to a pair (key, value).
>>> from collections import defaultdict
>>> res = defaultdict(int)
>>> for el in list1:
... k, v = el.split(':')
... res[k]+=int(v)
...
>>> res
defaultdict(<class 'int'>, {'a': 10, 'b': 17, 'c': 7})

How to get the key from value in a dictionary in Python? [duplicate]

This question already has answers here:
Get key by value in dictionary
(43 answers)
Closed 5 years ago.
d[key] = value
but how to get the keys from value?
For example:
a = {"horse": 4, "hot": 10, "hangover": 1, "hugs": 10}
b = 10
print(do_something with 10 to get ["hot", "hugs"])
You can write a list comprehension to pull out the matching keys.
print([k for k,v in a.items() if v == b])
Something like this can do it:
for key, value in a.iteritems():
if value == 10:
print key
If you want to save the associated keys to a value in a list, you edit the above example as follows:
keys = []
for key, value in a.iteritems():
if value == 10:
print key
keys.append(key)
You can also do that in a list comprehension as pointed out in an other answer.
b = 10
keys = [key for key, value in a.iteritems() if value == b]
Note that in python 3, dict.items is equivalent to dict.iteritems in python 2, check this for more details: What is the difference between dict.items() and dict.iteritems()?

Python remove a key from dictionary when It's a number [duplicate]

This question already has answers here:
Filter dict to contain only certain keys?
(22 answers)
Closed 6 years ago.
I'm trying to iterate over a dictionary in order to delete all items where the key is a number.
dict= {'hello':'3', 'baby':'5', '33':'6'}
for k in dict.keys():
if k.isdigit():
del dict[k]
The result i need is this:
dict={'hello':'3', 'baby':'5'}
I use the code above but it doesn't work?
Can somebody help me?
Instead of deleting items while looping through the dictionary, you can create a new dictionary:
dict_ = {'hello':'3', 'baby':'5', '33':'6'}
{k: v for k, v in dict_.items() if not k.isdigit()}
# {'baby': '5', 'hello': '3'}
The error RuntimeError: dictionary changed size during iteration, as it said, is raised because the dictionnary is modified during the iteration. One solution could be to first register all the keys, then modify the dictionnary:
dict= {'hello':'3', 'baby':'5', '33':'6'}
for k in tuple(dict.keys()): # iterate on a tuple of values that happened to be in dict's keys
if k.isdigit():
del dict[k]
The other, more pythonic, is to build the dictionnary in place, for instance using the dictionnary in intension notation like in this answer.
Btw, dict is a very bad name for an object of type dict.
The problem is because you are updating the dictionary while traversing. Rather first store the keys in a list and then remove from the dictionary.
Try this:
dic= {'hello':'3', 'baby':'5', '33':'6'}
x=dic.keys()
for k in x:
if k.isdigit():
del dic[k]
print dic
output :
{'baby': '5', 'hello': '3'}
Here is another solution using pop and map to modify in place your initial dictionary:
my_dict = {'a':1, 'b':2, 'c':3, '11':4, '12':5}
_ = map(lambda k: my_dict.pop(k), [k for k in my_dict if k.isdigit()])
# The map functions modifies in place your dictionary
Output :
>> my_dict
>> {'a': 1, 'b': 2, 'c': 3}

Flip a Dictionary - Python? [duplicate]

This question already has answers here:
switching keys and values in a dictionary in python [duplicate]
(10 answers)
Closed 6 years ago.
I am currently preparing for a python exam and one topic we are expected to understand is having to flip a dictionary in which values become the keys and the keys become values. I am confused as to what this asking and if someone could provide me with a basic example to see what it looks like I would greatly appreciate it.
Simply write a dict comprehension expression and make it's key as value and values as key. For example:
>>> my_dict = {1: 2, 3: 4, 5: 6}
>>> {value: key for key, value in my_dict.items()}
{2: 1, 4: 3, 6: 5}
Note: Since, dict contains unique keys. In case you have same element as value for multiple keys in your original dict, you will loose related entries. For example:
# Same values v v
>>> my_dict = {1: 2, 3: 4, 5: 2}
>>> {value: key for key, value in my_dict.items()}
{2: 5, 4: 3}
#^ Only one entry of `2` as key

Delete items in a dictionary with values that don't equal the highest value in Python

Essentially I want to delete every key in a dictionary if its value doesn't equal the highest value.
Let's say this is the dictionary:
myDict = {"Bob": 1, "Bill": 5, "Barry": 4, "Steve": 5}
I'm able to sort it by value using this:
myDict = sorted(myDict, key=myDict.get, reverse=True)
Now I want to remove any key in the dictionary that doesn't equal the highest value (in this case '5'). To end up with this:
myDict = {"Bill": 5, "Steve": 5}
I've tried using this for loop:
for item, v in myDict:
if v < myDict[0]:
del myDict[v]
But I get this error:
ValueError: too many values to unpack (expected 2)
This is a) my first time posting here, and b) I've only been learning Python for a few months so I'm sorry if I've made any stupid mistakes.
for item, v in myDict just give you keys mydict, and you are collecting that key in item, v that's why,
use myDict.items() or myDict.iteritems().
for item, v in myDict.iteritems():
if v < myDict[0]:
del myDict[v]
To get Highest value of myDict
max(myDict.values())
To delete keys from Dict never change the iterator you are iterating on, it will give you RuntimeError. So copy it in another variable and change previous one as Anand S Kumar suggested.
You should never alter the object you're iterating over, that usually yields unexpected results (internal pointers get shifted and you miss elements in your iteration and such). You best gather the keys you want to delete and then remove the keys in a separate iteration:
keys = [k for k in myDict.keys() if myDict[k] == max(myDict.values())];
for k in keys: del myDict[k];
It might be best to put the max expression in a variable too so it doesn't get evaluated multiple times. Not sure if Python's able to optimize that for you (probably not).
You can use dictionary comprehension to create a new dictionary:
newDict = {k: v for k,v in myDict.items() if v == max(myDict.values())}
The output for newDict:
{'Steve': 5, 'Bill': 5}

Categories

Resources