简体   繁体   中英

Divide list elements with dictionary values in python

I have a dictionary as:

d=[{'court': 4, 'hope': 6},
 {'court': 9, 'hope': 27},
 {'hope': 5, 'mention': 2, 'life': 10, 'bolster': 1, 'internal': 15, 'level': 1}]

and list

l=[2, 9, 5]

All I want to divide the list elements with correponding dictionary values. something,

new_list=[{'court': 2, 'hope': 3},
 {'court': 1, 'hope': 3},
 {'hope': 1, 'mention': 0.4, 'life': 2, 'bolster': 0.2, 'internal': 3,'level': 0.2}]

All I did,

new_list=[]
for i in d:
    for k,j in i.items():
        new={k:j/o for o in l}
        new_list.append(new)

it returns as list with individual elements:

[{'court': 2},{'hope': 3},
 {'court': 1},{'hope': 3},
 {'hope': 1},{'mention': 0.4},{'life': 2},{'bolster': 0.2},{'internal': 3},{'level': 0.2}]

With simple list/dict comprehension:

res = [{k: v/divider for k,v in d[i].items()} for i, divider in enumerate(l)]
print(res)

The output:

[{'court': 2.0, 'hope': 3.0}, {'court': 1.0, 'hope': 3.0}, {'hope': 1.0, 'mention': 0.4, 'life': 2.0, 'bolster': 0.2, 'internal': 3.0, 'level': 0.2}]

Or the same with zip function:

res = [{k: v/divider for k,v in d.items()} for d, divider in zip(d, l)]

1. Hard Way(most understandable way)

for i in range(len(l)):
     for key, value in d[i].items():
          val = value / l[i]
          if val.is_integer():
               d[i][key] = int(val)
          else:
               d[i][key] = val

print(d)

2. using zip() python Built-in Functions

d = [{key: (int(value/divider) if (value/divider).is_integer() else value/divider) for key,value in d.items()} for d, divider in zip(d, l)]
print(d)

3. using enumerate() python Built-in Functions

d = [{key: (int(value/divider) if (value/divider).is_integer() else value/divider) for key,value in d[i].items()} for i, divider in enumerate(l)]
print(d)

Those 3 methods giving you the same output which you expected:

[{'court': 2, 'hope': 3},
 {'court': 1, 'hope': 3},
 {'hope': 1, 'mention': 0.4, 'life': 2, 'bolster': 0.2, 'internal': 3, 'level': 0.2}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM