How to calculate in list of dictionaries based on assigning the values for its keys in another dictionary?
How to do this for the following input, print in descending order of bid based on summation of value of itype in coef
class ininput(NamedTuple):
itype: str
bid: int
coefficient= {'dr e': 2.0,'ph': 1.0,'c-in': 0.8,'bk': 0.25}
def calvalue(ininputs: Iterable[ininput]) -> List[int]:pass
outf=[]
v=sorted(ininputs, key='bid')
for ininput in ininputs:
for i in v:
if ininput.bid==i:
x=ininput.itype
outf.append(sum(coefficient[x]))
outf=sorted(outf,reverse=True)
return outf
def main():
ininput=[{"itype":"ph","bid":1},{"itype":"bk","bid":2},{"itype":"c_in","bid":3},{"itype":"dr e","bid":4},{"itype":"c_in","bid":4}]
sortbid = calvalue(ininputs)
for bid in sortbid:
print(bid)
if __name__ == '__main__':
main()
Sample input:
coefficient= {'dr e': 2.0,'ph': 1.0,'c-in': 0.8,'bk': 0.25}
ininput=[{"itype":"ph:,"bid":1},{"itype":"bk","bid":2},{"itype":"c_in","bid":3},{"itype":"dr e","bid":4},{"itype":"c_in","bid":4}]
In order to calculate output:
calculation for given input is based on coefficient values, therefore for each bid we should calculate:
For bid=1=> itype= ph, the coefficient of ph is 1
For bid=2=> itype= bk, the coefficient of bk is 0.25
For bid=3=> itype= c-in, the coefficient of c-in is 0.8
For bid=4=> itype= c-in && itype= dr e , the coefficient of them are 2 (dr e) 0.8 (c_in)=2.8
Sample Output:(based on above calculation)
Then, sort the bid based on descending order of above calculation
[4,1,3,2]
CodePudding user response:
- Fix typos like:
c-in in coefficient while c_in in ininput
"itype":"ph:," -> "itype": "ph"
sortbid = calvalue(ininputs) -> sortbid = calvalue(ininput)
2.
coefficient= {'dr e': 2.0, 'ph': 1.0, 'c_in': 0.8, 'bk': 0.25}
def calvalue(ininputs):
# initialize a sum dict with 0
sum_dict = {_["bid"]: 0 for _ in ininputs}
# add according to "itype"'s value
for _ in ininputs:
sum_dict[_["bid"]] = coefficient[_["itype"]]
# sort and reverse
sorted_bid = sorted(sum_dict, key=sum_dict.get)[::-1]
return sorted_bid
def main():
ininput = [
{"itype": "ph", "bid": 1},
{"itype": "bk", "bid": 2},
{"itype": "c_in", "bid": 3},
{"itype": "dr e", "bid": 4},
{"itype": "c_in", "bid": 4}
]
sortbid = calvalue(ininput)
print(sortbid)
if __name__ == "__main__":
main()
Outcome:
[4, 1, 3, 2]
