英文:
How to update the string with priority order in the dictionary
问题
data = [
{'Pencil': 'Green'},
{'Pen': 'N/A'},
{'Scale': 'Red'},
{'Compass': 'N/A'}
]
priority_order = {'Red': 4, 'Orange': 3, 'Yellow': 2, 'Green': 1, 'Undefined': 0}
main = 'Undefined'
for each in data:
for k, v in each.items():
if priority_order[v] > priority_order[main]:
main = v
英文:
I have list of dict below
data =
[ { 'Pencil': 'Green' }, { 'Pen': 'N/A' }, { 'Scale': 'Red' }, { 'Compass': 'N/A'}]
My priority order is below
priority_order = {'Red':4, 'Orange':3, 'Yellow':2, 'Green':1, 'Undefined': 0}
I have main variable which has to update with in priority order of values in data
list of dictionary, by default main is
main = 'Undefined'
Code is below
for each in data:
for k,v in each.items():
if priority_order[v] > priority_order[main]:
main = priority_order[v]
I am getting key error for this
My expected out is 'Red' as scale
is having 'Red'
答案1
得分: 3
data = [{'Pencil': '绿色'}, {'Pen': 'N/A'}, {'Scale': '红色'}, {'Compass': 'N/A'}]
priority_order = {'红色': 4, '橙色': 3, '黄色': 2, '绿色': 1, 'N/A': 0}
main = 'N/A'
for each in data:
for k, v in each.items():
if priority_order[v] > priority_order[main]:
main = v
print(main)
英文:
data =[ { 'Pencil': 'Green' }, { 'Pen': 'N/A' }, { 'Scale': 'Red' }, { 'Compass': 'N/A'}]
priority_order = {'Red':4, 'Orange':3, 'Yellow':2, 'Green':1, 'N/A': 0}
main = 'N/A'
for each in data:
for k,v in each.items():
if priority_order[v] > priority_order[main]:
main = v
print(main)
答案2
得分: 0
for each in data:
for k, v in each.items():
if v in priority_order:
if priority_order[v] > priority_order[main]:
main = v
英文:
for each in data:
for k, v in each.items():
if v in priority_order:
if priority_order[v] > priority_order[main]:
main = v
This should do the trick.
答案3
得分: 0
你可以使用一个简单的 max()
调用来实现这个功能:
data =[ { 'Pencil': 'Green' }, { 'Pen': 'N/A' }, { 'Scale': 'Red' }, { 'Compass': 'N/A'}]
priority_order = {'Red':4, 'Orange':3, 'Yellow':2, 'Green':1, 'N/A': 0}
print(max((v for each in data for v in each.values()), key=priority_order.get))
输出结果为:
Red
如果你希望它能处理不在 priority_order
中的值,可以指定一个提供默认优先级的 key
(因为默认值 None
在与整数比较时会引发 TypeError
):
print(max(
(v for each in data for v in each.values()),
key=lambda v: priority_order.get(v, 0)
))
英文:
You can do this with a simple max()
call:
data =[ { 'Pencil': 'Green' }, { 'Pen': 'N/A' }, { 'Scale': 'Red' }, { 'Compass': 'N/A'}]
priority_order = {'Red':4, 'Orange':3, 'Yellow':2, 'Green':1, 'N/A': 0}
print(max((v for each in data for v in each.values()), key=priority_order.get))
prints:
Red
If you want it to be able to handle values that aren't in priority_order
, specify a key
that supplies a default priority (since the default None
will raise a TypeError
on comparisons with ints):
print(max(
(v for each in data for v in each.values()),
key=lambda v: priority_order.get(v, 0)
))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论