This question already has answers here:
Grouping Python dictionary keys as a list and create a new dictionary with this list as a value
(2 answers)
Closed 2 years ago.
I have a dict like below.
{'I1': ['N1', 'N2', 'N3'],
'I2': ['N2', 'N4'],
'I3': ['N1', 'N2']}
I want to reverse it in the below format. (i.e group the above dict based on the value and map the key to it)
{'N1': ['I1','I3'],
'N2':['I1','I2','I3'],
'N3':'I1',
'N4': 'I2' }.
I tried this code
from collections import defaultdict
v = defaultdict(list)
for key, value in sorted(my_dict.items()):
v[value].append(key)
But its throwing error "unhashable type: 'list' "
How can I achieve this?
try this:
reversedict = dict([(value, key) for key, value in mydict.iteritems()])
Related
This question already has answers here:
How do I merge a list of dicts into a single dict?
(11 answers)
Closed 1 year ago.
I need to perform below operations:
iterate over a list of dictionary [{},{}]
call a transform function which transforms each dictionary, which returns a dictionary.
Here key and values are not static, but dataframe name and dataframe value. So dictionary may have one ore more key-value pair.
which I would need to store in a final dictionary
Expected : expected data would be a dictionary:
{"key1":"val1", "key2":"val2", "key3":"val3"} # ... in actual, the key would be dataframe name, value would be dataframe value
Simplified Use case:
dictname = [{"key1":"val1","key2":"val2"},{"key3":"value3"}] # input list of dictionary
def transform(each):
return each # to oversimplify, this would be a dictionary with one or more keys with transformations.
final = {transform(each) for each in dictname}
final
went over other related threads on the issue, could not figure out as how to handle the specific case. Could anyone please guide?e
There are several things wrong in your code.
The dict comprehension is as follows: {key: value, for key, value in something that outputs two things}. In your case transform_each outputs a dict. So fixing this we obtain:
dictname = {"key1":"val1","key2":"val2"} # input dictionary
def transform(each):
return {each: "new_value"}
final = {key: transform(each) for key, each in dictname.items()}
final # {'key1': {'val1': 'new_value'}, 'key2': {'val2': 'new_value'}}
This is not what you want. You need to change only the value of the dict. That is the second thing wrong: Your function must output a value, not a dict. Otherwise, as seen, you got a dict of dicts. You can fix it as follows:
dictname = {"key1":"val1","key2":"val2"} # input dictionary
def transform(each):
return "new_value"
final = {key: transform(each) for key, each in dictname.items()}
final # {'key1': 'new_value', 'key2': 'new_value'}
Define transform as
def transform(each):
return <the new value>
and then use
result = {k: transform(k) for k in dictname}
If you cannot update transform use
from collections import ChainMap
result = dict(ChainMap(*(transform(k) for k in dictname)))
This is an updated answer for the updated question. I think the following should do what you want:
dictname = [{"key1":"val1", "key2":"val2"}, {"key3":"val3"}]
def transform(each):
return each
final = {k:v for d in dictname for k, v in transform(d).items()}
The transform function takes one of the dictionaries as an argument, and returns a dictionary. The returned dictionaries from all the calls to transform are combined into the top-level dictionary final.
The example above defined final to be:
{'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
In this example, transform merely returns the dict that was passed to it, but it could return any dict you want.
This question already has answers here:
How to reverse a dictionary that has repeated values
(7 answers)
Closed 1 year ago.
I got an python interview question:
#Dictionary
Convert
i = {"volvo":"car", "benz":"car", "yamaha":"bike", "hero":"bike"}
in to
output = {"car":["volvo", "benz"], "bike":["yamaha", "hero"]}
You can use the try/except process to reorder the dictionary.
i = {"volvo":"car", "benz":"car", "yamaha":"bike", "hero":"bike"}
output ={}
for k, it in i.items():
try:
output[it].append(k)
except KeyError:
output[it] = [k]
print(output)
Output:
{'car': ['volvo', 'benz'], 'bike': ['yamaha', 'hero']}
This question already has answers here:
Update python dictionary (add another value to existing key)
(8 answers)
Closed 2 years ago.
I am trying to append a value to a key that already exists in a dict.
I came across this SO link How do I append a value to dict key? (AttributeError: 'str' object has no attribute 'append') however in this particular case the values were integers while in my case the values are strings.
What I want is:
mydict = {'ADE':'AD', 'RS':'S'}
key1 = 'ADE'
value1 = 'AE'
if key1 in mydict:
mydict[key1].append(value1)
else:
mydict[key1] = value1
I want to append to mydict['ADE'] so that it equals ['AD','AE'].
However, that generates a AttributeError: 'str' object has no attribute 'append'
I even tried the following:
from collections import defaultdict
d = defaultdict(list)
mydict = {'ADE':'AD', 'RS':'S'}
for key, value in mydict.items():
d[key] = value
d then = defaultdict(list, {'ADE': 'AD', 'RS': 'S'})
Then I run the following:
key1 = 'ADE'
value1 = 'AE'
if key1 in d:
d[key1].append(value1)
else:
d[key1] = value1
But I get the same error: AttributeError: 'str' object has no attribute 'append'
mydict[key1] is a string (a str object - an object of class str). mydict[key1].append(value1) attempts to call the append method of this str object.
str objects do not have the append method, which is exactly what the error message is telling you: "'str' object has no attribute 'append'".
If you want to append data to something, use a collection, like a list:
mydict = {'ADE': ['AD'], 'RS': ['S']}
if key1 in mydict:
mydict[key1].append(value1)
else:
mydict[key1] = [value1]
As the key ADE is present, the list factory is unused, and so the error becomes inevitable.
You may use the list factory at the very beginning, and so the if .. in .. is useless as the purpose of a defaultdict is to avoir checking that by yourself
from collections import defaultdict
d = defaultdict(list)
mydict = {'ADE': 'AD', 'RS': 'S'}
for key, value in mydict.items():
d[key].append(value)
key1 = 'ADE'
value1 = 'AE'
d[key1].append(value1)
print(d) # defaultdict(<class 'list'>, {'ADE': ['AD', 'AE'], 'RS': ['S']})
what do you mean by append the value?
ADE is the key and AE is the value. are you trying to change the value to AD?
or are you trying to do something like AE+AD = AEAD and assign it to ADE key?
you question is not clear.
The error you are getting is becuase d[key1] is a string value. string type does not have append function to it.
This question already has answers here:
How do I sort a dictionary by value?
(34 answers)
Closed 2 years ago.
I have a variable.
Score = {}
After some calculation, the value of Score is :
{
'449 22876': 0.7491997,
'3655 6388': 0.99840045,
'2530 14648': 0.9219989,
'19957 832': 0.9806836,
'2741 23293': 0.64072967,
'22324 7525': 0.986661,
'9090 3811': 0.90206504,
'10588 5352': 0.8018138,
'18231 7515': 0.9991332,
'17807 14648': 0.9131582
.....
}
I want to sort it by the third value(e.g. 0.7491997).
I only want to get the top 100 high score.
How can I do?
if you want to sort the dictionary by the values of the dictionary (which is what I am getting from your question) you could do it with this lambda function:
sorted_dict = sorted(score.items(), key=lambda x: x[1])
This question already has answers here:
How to set default value to all keys of a dict object in python?
(7 answers)
Closed 2 years ago.
For example, if a dictionary is defined pythonDict = {a: 1, b: 2} and it is referenced pythonDict["c"] or pythonDict["d"], can the dictionary be defined a default value for any key that isn't listed, without listing all the possibilities?
I'd like to have a reference in one line without an additional "if" statement to check if the key is included.
Use a defaultdict
>>> from collections import defaultdict
>>> pythonDict = defaultdict(lambda: 100, a=1, b=2)
>>> pythonDict["c"]
100
Use dict.get(key, default value).
It returns value when key is in dict. Otherwise, it returns default value.
Example code.
dic = {"a":1, "b":2}
my_default = "default"
print(dic.get("a", my_default))
print(dic.get("c", my_default))