Delete certain values from a dictionary? - python

I want to delete the keys in my dictionary with the value of 1, but the only way I know of is to manually input keys to delete which is inefficient. Any ideas?
I have a feeling I should use:
for key,value in mydict.items():
For example, if I had the dictionary
mydict = {'a':1, 'b':2, 'c':3, 'd':1, 'e':1}
how would I delete the keys with a value of 1 so that I can print a dictionary purely of keys with values > 1?

You can use a dict comprehension to filter the dictionary:
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':1, 'e':1}
>>> {k:v for k,v in mydict.items() if v != 1}
{'c': 3, 'b': 2}
>>>
Note that you should use mydict.iteritems() if you are on Python 2.x to avoid creating an unnecessary list.

You could go though each of the items (the key value pair) in the dictionary to check the conflict and add value in new Dict.(here.. result) that not contain duplicate.
mydict = {'a':1, 'b':2, 'c':3, 'd':1, 'e':1}
result = {}
for key,value in mydict.items():
if value not in result.values():
result[key] = value
print result

To create a new dictionary with the items which has the value greater than 1 use dict comprehension like below.
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':1, 'e':1}
>>> {key:value for key,value in mydict.items() if value > 1}
{'c': 3, 'b': 2}

Related

How to create nested dictionary using two dictionaries in which value of first dictionary is equal to the key of second dictionary

In my Project, 2 dictionaries have been created in below format :-
dict1 = {'A':['B'], 'C':['D']}
dict2 = {'B':['X'], 'D':['Y']}
And I'm looking for below expected result :-
dict3 = {'A':{'B':['X']}, 'C':{'D':['y']}}
I want to print value of 'A', 'B' and 'X' in 3 columns in HTML table but somehow I'm not able to do so. Please help me out to get this.
Thanks in advance..!!
Does this works for you:
dict1 = {'A':['B'], 'C':['D']}
dict2 = {'B':['X'], 'D':['Y']}
new_dict = dict()
for val1, val2 in dict1.items():
new_dict[val1] = {val2[0]:dict2[val2[0]]}
new_dict
{'A': {'B': ['X']}, 'C': {'D': ['Y']}}
You can try this way:
>>> dict3 = dict([(k,{v[0]:dict2[v[0]]}) for k, v in dict1.items()])
>>> dict3
{'A': {'B': ['X']}, 'C': {'D': ['Y']}}

how to merge 2 dictionaries into a new dictionary in python

I'm trying to write a function that merges the items in multiple dictionaries under a single dictionary for matching keys.
For example, given
dict1 = {1:3, 2:4}
dict2 = {1:5, 2:6}
the function must return:
dict3 = {1:(3,5),2:(4,6)}
I also want the values to be numerically sorted, i.e. like this:
{1:(3,5)}
instead of this:
{1:(5,3)}
So far, I tried this, but it didn't work as I expected:
def mergeDicts(dict1, dict2):
dict3 = {**dict1, **dict2}
for key, value in dict3.items():
if key in dict1 and key in dict2:
dict3[key] = (value , dict1[key])
return dict3
You may use a defaultdict and a list as type of value, then iterate both dict1 and dict2 and their value in the list pointed by the key
def mergeDicts(dict1, dict2):
dict3 = defaultdict(list)
for key, value in dict1.items():
dict3[key].append(value)
for key, value in dict2.items():
dict3[key].append(value)
return dict(dict3)
Generic method that can accept any amount of dict as parameters
def mergeDicts(*dicts):
dict3 = defaultdict(list)
for d in dicts:
for key, value in d.items():
dict3[key].append(value)
return dict(dict3)
Achieving the same with dict-comprehension
def mergeDicts(dict1, dict2):
return {k: [dict1[k], dict2[k]] for k in dict1}
def mergeDicts(*dicts):
return {k: [d[k] for d in dicts] for k in dicts[0]}
You can do like this:
dict1 = {1:3, 2:4}
dict2 = {1:5, 2:6}
ds = [dict1, dict2]
d = {}
for k in dict1.iterkeys():
d[k] = tuple(d[k] for d in ds)
print(d)
I believe this is closer to what you want than the other answer.
def mergeDicts(dict1, dict2):
dict3 = {}
for key, value in dict1.items():
if key in dict2:
dict3[key] = (value, dict2[key])
return dict3
You could do it lke this:
dict1 = {1:3, 2:4}
dict2 = {1:5, 2:6}
def mergeDicts(dict1, dict2):
dict3 = {}
for key, value in dict1.items():
dict3[key] = (value, dict2[key])
return dict3
Assume keys are going to be same in both dictionary
def mergeDicts(dict1, dict2):
dict3 = {}
for i in dict1.keys():
dict3[i] = dict1[i], dict2[i]
return dict3
Assuming the dicts might have fully/partially different keys:
def mergeDicts(d1:dict, d2:dict):
keys=set(list(d1.keys())+list(d2.keys()))
keys_inter=set(d1.keys()).intersection(d2.keys())
d=dict()
for k in keys:
d[k]=[d1[k], d2[k]] if k in keys_inter else [(d1.get(k, None) or d2.get(k, None))]
return d
The following provides exactly the output that you are seeking.
from collections import defaultdict
from itertools import chain
dict1 = {1:3, 2:4}
dict2 = {1:5, 2:6}
dict3 = defaultdict(list)
for (k,v) in chain(dict1.items(), dict2.items()):
dict3[k].append(v)
for k in dict3.keys():
dict3[k] = tuple(dict3[k])
output
defaultdict(<class 'list'>, {1: (3, 5), 2: (4, 6)})

correcting unhashable type: 'dict_keys'

try to find the max value in a nested dictionary, but showed unhashable type: 'dict_keys'error
Suppose I have this dictionary:
d = {'A': {'a':2, 'b':2, 'c':0},
'B': {'a':2, 'b':0, 'c':1}}
I want the code to return all the key(s) that contain maximum values within the dictionary (i.e. the maximum value in dictionary A is 2, and I want the code to return me the corresponding keys: 'a' and 'b')
['a','b']
here is the code I wrote:
max_value = max(d[Capital_Alph].values()))
return [key for key, value in d[Capital_Alph].items()
if value == max_value]
So you have a dictionary with a str as value and a dict as key, You can do something like this:
d = {'A': {'a':2, 'b':2, 'c':0},
'B': {'a':2, 'b':0, 'c':1}}
print(list(d['A'].keys()))
Returns:
['a', 'b', 'c']
[Finished in 0.8s]
Is this a viable solution to what you are trying to accomplish?
You can not use non-hashable datatypes as keys for sets or dict. You can accomplish your task by:
d = {'A': {'a':2, 'b':2, 'c':0},
'B': {'a':2, 'b':0, 'c':1}}
max_v = {k:max(d[k].values()) for k in d } # get the max value of the inner dict
print(max_v)
for inner in max_v:
print("Max keys of dict {} are: {}".format(inner,
[k for k,v in d[inner].items() if v == max_v[inner]]))
Output:
{'A': 2, 'B': 2} # max values of inner dicts
Max keys of dict A are: ['a', 'b']
Max keys of dict B are: ['a']
The part [k for k,v in d[inner].items() if v == max_v[inner]])) is needed to get all inner keys (if multiple exists) that have the same maximum value.
There are two errors in your code: there are too many ) characters in your calculation of max_value and you can't use return outside a function.
But if I fix those issues and do this:
>>> d = {'A': {'a':2, 'b':2, 'c':0},
'B': {'a':2, 'b':0, 'c':1}}
>>> Capital_Alph = "A"
>>> max_value = max(d[Capital_Alph].values())
>>> [key for key, value in d[Capital_Alph].items()
if value == max_value]
['a', 'b']
it's clear that there isn't a lot else wrong here. To avoid complicating things I didn't put the obvious loop around this:
for Capital_Alph in d:
but you can manage that on your own. Your error message is because you tried to make Capital_Alph a dict_keys object, in other words d.keys(), and use that as a key. You can't do that. You have to step through the list of dictionary keys yourself.

Weave two dictionaries into one

I have two dictionaries:
dict1 = {'a': 1,
'b': 2,
'c': 3,
'd': 4,
'x': 5}
and
dict2 = {'a': 'start',
'b': 'start',
'c': 'end',
'd': 'end'}
I am trying to create a new dictionary that maps the values start and end as keys to a dictionary that would contain the info of dict1, while keeping those that are not present in dict2 as keys, e.g.:
dict3 = {'start': {'a': 1, 'b': 2},
'end': {'c': 3, 'd': 4},
'x': {'x': 5}
}
Use dict.setdefault() to create the nested dictionaries in dict3 if not yet there, and dict.get() to determine the key in the top-level output dictionary:
dict3 = {}
for k, v in dict1.items():
nested = dict3.setdefault(dict2.get(k, k), {})
nested[k] = v
So dict2.get(k, k) will produce the value from dict2 for a given key from dict1, using the key itself as a default. So for the 'x' key, that'll produce 'x' as there is no mapping in dict2 for that key.
Demo:
>>> dict3 = {}
>>> for k, v in dict1.items():
... nested = dict3.setdefault(dict2.get(k, k), {})
... nested[k] = v
...
>>> dict3
{'start': {'a': 1, 'b': 2}, 'end': {'c': 3, 'd': 4}, 'x': {'x': 5}}
I actually figured it out while abstracting the example and typing up my question here (should have maybe done this earlier...). Anyways: Yay!
So here is my solution, in case it may help someone. If someone knows a swifter or more elegant way to do it, I would be glad to learn!
dict3 = dict()
for k, v in dict1.items():
# if the key of dict1 exists also in dict2
if k in dict2.keys():
# get its value (the keys-to-be for the new dict3)
new_key = dict2[k]
# if the new key is already in the new dict
if new_key in dict3.keys():
# appends new dict entry to dict3
dict3[new_key].update({k: v})
# otherwise create a new entry
else:
dict3[new_key] = {k: v}
# if there is no corresponding mapping present
else:
# treat the original key as the new key and add to dict3
no_map = k
dict3[no_map] = {k: v}

How to remove dictionary key with known value?

Assume python dict:
mydict = {'a': 100, 'b': 200, 'c': 300}
I know one of the values:
value = 200
How to remove the 'b': 200 pair from the dict? I need this:
mydict = {'a': 100, 'c': 300}
Use a dictionary comprehension. Note that (as jonrsharpe has stated) this will create a new dictionary which excludes the key:value pair that you want to remove. If you want to delete it from your original dictionary then please see his answer.
>>> d = {'a': 100, 'b': 200, 'c': 300}
>>> val = 200
# Use d.items() for Python 2.x and d.iteritems() for Python 3.x
>>> d2 = {k:v for k,v in d.items() if v != val}
>>> d2
{'a': 100, 'c': 300}
It sounds like you want:
for key, val in list(mydict.items()):
if val == value:
del mydict[key]
break # unless you want to remove multiple occurences
You'll need to loop over every items(), either with dict comprehension:
new_dict = {k:v for k,v in my_dict.items() if predicate(value)}
Or modifying the existing dictionary:
for k,v in my_dict.items():
if not predicate(v):
del my_dict[k]
The simplest i found:
for key in [k for k,v in mydict.items() if v==200]:
del mydict[key]

Categories