I have a dictionary
TestDict = {'Group1': 'Crew 1', 'Group2': 'Crew 2', 'Group3': 'Crew 3'}
And I'd like to edit the value in the dictionary to have this desired output
{'Group1': 'Group1_Crew_1', 'Group2': 'Group2_Crew_2', 'Group3': 'Group3_Crew_3'}
So in the above, the key is now a part of the value and the space have been replaced with _
So far I've only tried to tackle appending the key to the value with
for key, value in TestDict.items():
newDict = {key: key + "_" + value for key in TestDict}
Problematically, this outputs in the proper dictionary, however, all of the values are Group3_Crew 3. I'm not sure how to navigate this issue.
You have two options:
Create a new dictionary and update it content:
newDict = {}
for key, value in TestDict.items():
newDict[key] = key + "_" + value.replace(" ", "_")
or use a dict comprehension:
newdDict = {key: key + "_" + value.replace(" ", "_") for key in TestDict}
You were like mixing both concepts.
You have two problems.
Firstly, you're iterating over TestDict twice, where you only need to do so once. You're recreating an entire new version of newDict each time through the loop and, after you're done, you're only seeing the last one created.
Use either
newDict = {}
for key, value in TestDict.items():
newDict[key] = key + "_" + value
or
newDict = {key: key + "_" + value for key, value in TestDict.items()}
but don't combine both.
(The results you're seeing are because you're getting a new key in each inner iteration, but only a single value from the outer iteration.)
Also, you're not replacing spaces with underscores, which you would do by replacing value with value.replace(' ', '_') in either version.
You can use:
{k: k+'_'+v.replace(' ', '_') for k, v in TestDict.items()}
Related
I am new to python and I want to know how to find out that a key is a substring of another keys in a dictionary. Example that I have a dictionary:
dictionary = {'modulus of elasticity': 24, 'cross validation': 16, 'mechanical properties': 16, 'elasticity': 2}
The code I have tried:
for k in dictionary.keys():
res = [ d for d in dictionary.keys() if d in k ]
if res:
if(len(d) > len(k)):
print(d,"is longer than ", k)
else:
pass
For my code I know it will get error that NameError: name 'd' is not defined as in fact I dont know how to capture the value of k and d when there is a substring between them. In my case I want to loop through the key in the dictionary and verified that if a current key is the substring of another key in the whole dictionary. For example, if the first key like modulus of elasticity I want to check that the other keys beside itself is containing it or not until the end of dictionary and of course when we loop until elasticity we will see that elasticity is the substring of modulus of elasticity but not vice-versa. In this case I want to capture both the key elasticity and key modulus of elasticity to print in the if statement: modulus of elasticity is longer than elasticity or in the other cases, I want to also manipulate their values. How to do this? Any help would be much appreciated! Thanks!
What you need to do is:
Get all keys from dictionary.
For each key, search to see if it's a substring of another key. If this is the case, print it. Else move on to the next one.
keys = list(dictionary.keys())
for key in keys:
for other_key in keys:
if key == other_key:
continue
else:
if key in other_key:
print(key + ' is a substring of ' + other_key)
d is only defined inside the list comprehension, here is a simpler way to accomplish that:
dictionary = {'modulus of elasticity': 24, 'cross validation': 16, 'mechanical properties': 16, 'elasticity': 2}
for k in dictionary.keys():
for k2 in dictionary.keys():
if k != k2 and k in k2: print(k2 ,"is longer than ", k)
>>> modulus of elasticity is longer than elasticity
We loop two times through the keys of the dictionary and we check if they are not the same key, otherwise we validate if one is a substring of the other one.
You don't have to scan from the beginning of the list each loop iteration, this is just extra CPU cycles, instead, sort the list by keys'length, then on each iteration start from the next item of the current iteration value, as per the following code:
>>> keys = sorted(dictionary.keys(), key=lambda k: len(k))
>>>
>>> for index, key_out in enumerate(keys):
for key_in in keys[index+1:]:
if (key_out in key_in) and (key_out != key_in):
print('[' + key_out + ']' + ' is a substring of [' + key_in + ']')
[elasticity] is a substring of [modulus of elasticity]
I have a JSON file having key value pairs. Currently I'm using python built in Replace() function to replace spaces with underscore but it also replace spaces with underscore in values.I only want to replace spaces from Keys, Values should remain the same.
This is the python function I'm using
string=string.replace(" ","_")
The assumption I am working under is that you first convert the Json string to a dictionary. Then:
The most pythonic (idiomatic, clearest and efficient) way to do this is with a dictionary comprehension:
d = {"key 1": "Value 1", "key 2": "value 2"}
new_d = {k.replace(" ", "_"): v for k, v in d.items()}
print(new_d)
Prints:
{'key_1': 'Value 1', 'key_2': 'value 2'}
d.items() iterates all the key/value pairs of the dictionary as variables k and v in the above code and after the spaces are replaced with underscores in k, a new dictionary is created from these k and v pairs.
You can then convert the dictionary back to a Json string.
You cannot change the keys. What you can do is add the modified key, value pair and then remove the old one.
Let's say you have a dictionary like below:
{'x c': 'z c'}
You can write following script to replace whitespaces in keys:
x = {"x c":"z c"}
for key,value in x.iteritems():
new_key = key.replace(" ","_")
del x[key] # Deleting Previous Key
x[new_key] = value # Adding Modified key
Output:
{'x_c': 'z c'}
Hope this helps you out!!!
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.
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}