Dictionary Conversion [duplicate] - python

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']}

Related

How do i turn a list into a dict? [duplicate]

This question already has answers here:
Convert [key1,val1,key2,val2] to a dict?
(12 answers)
Closed 8 months ago.
I'm making a Python(3) progam to read this text file:
firstval="myval"
secondval="myotherval"
and turn it into a dict.
I tried this:
lines = file.readlines().split("\n")
values = []
for line in lines:
values.append(line.split("="))
to turn the file into a list
How do i turn this:
values = ["firstval", "myval", "secondval", "myotherval"]
into this:
values = {
"firstval": "myval",
"secondval": "myotherval"
}
You can use dict() with zip():
dict(zip(values[::2], values[1::2]))
This outputs:
{'firstval': 'myval', 'secondval': 'myotherval'}

Reverse mapping in python [duplicate]

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()])

python how to sort a variable like {'a b': c, 'd e':f ....} [duplicate]

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])

Dictionary converted to array in python [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 2 years ago.
d={'a0': [['5021', '5031'], ['4994', '4991', '5042'],
['4992', '4995', '5021', '4994'], ['5037', '5038']],
'a24': [['5009', '5014'], ['5009', '5014'], ['4993', '4998', '5030', '4991']]
}
I have the above dict in python.
I need to make list with the name of it being the names of keys in the dict.
The list with the name of the key should have the items as its corresponding values in dict.
The output should be:
a0=[['5021', '5031'], ['4994', '4991', '5042'],
['4992', '4995', '5021', '4994'], ['5037', '5038']]
a24=[['5009', '5014'], ['5009', '5014'], ['4993', '4998', '5030', '4991']]
Any help is appreciated.
First, rethink if this is really necessary. Dynamically creating variables is confusing and does not occur often. It would be better to avoid this.
However, you can do it like this:
for name, val in d.items():
exec("{}={}".format(name,val))
for key, item in d.items():
print(str(key) + "=" + str(item))

Python String to dict while separator is '=' [duplicate]

This question already has answers here:
Splitting a semicolon-separated string to a dictionary, in Python
(6 answers)
Closed 5 years ago.
Hy i have a list of strings which look like:
atr = ['ID=cbs7435_mt', 'Name=cbs7435_mt', 'Dbxref=taxon:981350', 'Note=Pichia pastoris CBS 7435 mitochondrion%2C complete replicon sequence.', 'date=27-FEB-2015', 'mol_type=genomic DNA', 'organelle=mitochondrion', 'organism=Komagataella pastoris CBS 7435', 'strain=CBS 7435']
Now i want to create a dictionary which should look like:
my_dict = {'ID': 'cbs7435_mt', 'Name':'cbs7435_mt', ...}
Do someone has any advice how i could manage this?
Thanks already!
Simply split it with = and use dict()
my_dict = dict(i.split('=') for i in atr)
Use split() method of string to get Key and value for dictionary item.
Use for loop to iterate on given list input.
Demo:
>>> atr = ['ID=cbs7435_mt', 'Name=cbs7435_mt', 'Dbxref=taxon:981350']>>> result_dict = {}
>>> for item in atr:
... key, value = item.split("=")
... result_dict[key] = value
...
>>> result_dict
{'Dbxref': 'taxon:981350', 'ID': 'cbs7435_mt', 'Name': 'cbs7435_mt'}
>>>

Categories