I want to add a key to existing key value pair in a dictionary,
is the below code is the pythonic way to add a key to a key value pair in a dictionary ?
region = 'us-west-2'
A = {'m3.large': -1, 'm3.xlarge': -1}
B = {}
for key, value in A.items():
B[(key,region)] = A.get((key, region), 0) + value
print(B)
output:
{('m3.large', 'us-west-2'): -1, ('m3.xlarge', 'us-west-2'): -1}
Also how can I do the same thing but on the same dict and not on a new dict ?
print(A)
output:
{('m3.large', 'us-west-2'): -1, ('m3.xlarge', 'us-west-2'): -1}
Thanks
B = {}
for key, value in A.items():
B[(key,region)] = A.get((key, region), 0) + value
This can be done in one statement with a dict comprehension.
B = {(key,region): A.get((key, region), 0) + value for key, value in A.items()}
Also how can I do the same thing but on the same dict and not on a new dict ?
dict keys are immutable, so you can't really modify them per se. You could add all the new keys and delete the old ones, but that would be inferior to just creating a new dict as you are doing now.
Related
# Initialising list of dictionary
ini_dict = [{'a':5, 'b':10, 'c':90},
{'a':45, 'b':78},
{'a':90, 'c':10}]
# printing initial dictionary
print ("initial dictionary", (ini_dict))
# sum the values with same keys
result = {}
for d in ini_dict:
for k in d.keys():
result[k] = result.get(k,0) + d[k]
print("resultant dictionary : ", (result))
Can someone explain the program line by line
Creating a list of dictionary's
ini_dict = [{'a':5, 'b':10, 'c':90},
{'a':45, 'b':78},
{'a':90, 'c':10}]
Prints out the list with dictionary's
print ("initial dictionary", (ini_dict))
Creates a new dictionary
result = {}
Loop's through the List of dictionarys
for d in ini_dict:
so the first d would be {'a':5, 'b':10, 'c':90}
Loop's through the keys of that dict
for k in d.keys():
-> a, b and c
Creates or gets the same key in the result dict and adds the value from the current key. Default value for a new created key is 0.
result[k] = result.get(k,0) + d[k]
Prints out the result dict
print("resultant dictionary : ", (result))
the first line initialises a list of three dictionaries.
ini_dict = [{'a':5, 'b':10, 'c':90},
{'a':45, 'b':78},
{'a':90, 'c':10}]
next up, the dictionary is printed
print ("initial dictionary", (ini_dict))
finally, a weighted histogram is made of the dictionaries based on the keys of the elements within said dictionaries. This is done in three steps:
iterating over the list of dictionaries to get at each different dictionary.
for d in ini_dict:
remember: ini_dict is a list of dictionaries. when you for-loop over a list, the symbol (here d) becomes each of the dictionaries.
iterating over the keys in the dictionary. The method dict.keys() returns a list of keys, over which can be iterated.
for k in d.keys():
finally, for each key in the dictionary the corresponding key in the result dictionary is modified to add the new value. with result.get(k,0) the value for the key k in the result dictionary is fetched, but 0 is the default value if the key is not present.
result[k] = result.get(k,0) + d[k]
This just replaces the result with the previous result + the value in d.
At the end of this bit of code, the result dictionary has the added value of each of the keys.
I need to compare list with dictionary keys and make a new dictionary if they match. The problem is that I dont know how to maintain list order.
list = [cat, dog, horse, kitten]
dict = {dog: 1, cat: 5}
filter_dict = {}
for key, value in dict.items():
if key in list:
filter_dict[key] = value
print(filter_dict)
What I need:
filter_dict= {cat: 5, dog: 1}
What I get:
filter_dict = {dog: 1, cat: 5}
Assuming you are using a Python version later than or equal to 3.6 (dictionaries are guaranteed to maintain order), you should loop over the list when constructing your dictionary not the original dict if you wish the keys to be in the same order as in the list
Looping over the dict will always produce the keys in the same order as the original dict
for item in your_list:
if item in your_dict:
filter_dict[item] = your_dict[item]
This can be achieved with a comprehension
filter_dict = {key: your_dict[key] for key in your_list if key in your_dict}
I'm trying to strip a nested dict (only 1 level deep eg: some_dict = {'a':{}, b:{}} all all non-zero and none values.
However I'm not sure who to reassemble the dict properly, the below gives me a key error.
def strip_nested_dict(self, some_dict):
new_dict = {}
for sub_dict_key, sub_dict in some_dict.items():
for key, value in sub_dict.items():
if value:
new_dict[sub_dict_key][key] = value
return new_dict
You need to create the nested dictionary before accessing it:
for sub_dict_key, sub_dict in some_dict.items():
new_dict[sub_dict_key] = {} # Add this line
for key, value in sub_dict.items():
# no changes
(In order for new_dict[sub_dict_key][key] to work, new_dict must be a dictionary, & new_dict[sub_dict_key] also has to be a dictionary.)
This worked. Shame you can't just assign a nested value without having to create an empty for for each key first.
def strip_nested_dict(self, some_dict):
new_dict = {}
for sub_dict_key, sub_dict in some_dict.items():
new_dict[sub_dict_key] = {}
for key, value in sub_dict.items():
if value:
new_dict[sub_dict_key][key] = value
return new_dict
I have a set of reactions (keys) with values (0.0 or 100) stored in mydict.
Now I want to place non zero values in a new dictionary (nonzerodict).
def nonzero(cmod):
mydict = cmod.getReactionValues()
nonzerodict = {}
for key in mydict:
if mydict.values() != float(0):
nonzerodict[nz] = mydict.values
print nz
Unfortunately this is not working.
My questions:
Am I iterating over a dictionary correctly?
Am I adding items to the new dictionary correctly?
You are testing if the list of values is not equal to float(0). Test each value instead, using the key to retrieve it:
if mydict[key] != 0:
nonzerodict[key] = mydict[key]
You are iterating over the keys correctly, but you could also iterate over the key-value pairs:
for key, value in mydict.iteritems():
if value != 0:
nonzerodict[key] = value
Note that with floating point values, chances are you'll have very small values, close to zero, that you may want to filter out too. If so, test if the value is close to zero instead:
if abs(value) > 1e-9:
You can do the whole thing in a single dictionary expression:
def nonzero(cmod):
return {k: v for k, v in cmod.getReactionValues().iteritems() if abs(v) > 1e-9}
Its simple and you can it by below way -
>>> d = {'a':4,'b':2, 'c':0}
>>> dict((k,v) for k,v in d.iteritems() if v!=0)
{'a': 4, 'b': 2}
>>>
Replace if condition in you code with:
if mydict[key]:
nonzerodict[key] = mydict[key]
Your solution can be further simplified as:
def nonzero(cmod):
mydict = cmod.getReactionValues()
nonzerodict = {key: value for key, value in mydict.iteritems() if value}
I have a dictionary like this:
dct = {'one': 'value',
'two': ['value1','value2','value1'],
'three':['otherValue1','otherValue2','otherValue1'],
'dontCareAboutThisKey':'debug'}
I need to remove duplicate values from the lists. I wrote a function to do this:
no_dups = {}
for keys in dct:
if isinstance(dct[keys], list) and keys != 'dontCareAboutThisKey':
for value in dct[keys]:
if value not in no_dups.values():
no_dups[keys].append(value)
else:
no_dups[keys] = dct[keys]
I'm checking if value of the current key is a list. If no, it just 'copy' key to no_dups dictionary. If it is a list and not a key that I don't care about (there are no duplicates for sure) - it should check if current value already exists in no_dups.values() and append it to current key. Problem is that I'm getting an error:
KeyError: 'two:'
I know it's because I'm trying to add a value to non existing key but I have no idea how to deal with this and make it work.
I think the best way to deal with adding the key and appending at the same time is with dicts' setdefault() method:
no_dups.setdefault(keys,[]).append(value)
But rather than that, you can do this in a more neat way like this:
#remove duplicates
no_dups = {k:list(set(v)) if isinstance(v, list) and k != 'dontCareAboutThisKey' else v
for k,v in dct.items()} # or dct.iteritems() if using python2.x
That hack will, for key value combinations that pass the if test, convert the list into a set (removing duplicates) and then in a list again. For other key value combinations it will leave it intact.
dct = {'one': 'value',
'two': ['value1','value2','value1'],
'three':['otherValue1','otherValue2','otherValue1'],
'dontCareAboutThisKey':'debug'}
set(dct) returns a set, which is a list without duplicates:
for key, value in dct.items():
if not isinstance(value, basestring):
dct[key] = set(value)
If you need a new dictionary you could do:
new_dct = {}
for key, value in dct.items():
if not isinstance(value, basestring):
new_dct[key] = set(value)
else:
new_dct[key] = value
If You want to remove duplicates, just change You list to set, with set() function:
https://docs.python.org/2/tutorial/datastructures.html#sets
It automatically gives You unique set, then You can always change it back to list.