从python字典中获取值并逐个传递
我有下面提到的字典从python字典中获取值并逐个传递,python,python-2.7,Python,Python 2.7,我有下面提到的字典 a={'name':['test1','test2'],'regno':['123','345'],'subject': ['maths','science'],'standard':['3','4']} 我需要核实以下事项 每个值计数字典都应该匹配 一个接一个地从每个键获取值,并将其一个接一个地传递给我的另一个函数 我试过使用下面的代码,但我被困在这里,以找出确切的方法 a={'name':['test1','test2'],'regno':[
a={'name':['test1','test2'],'regno':['123','345'],'subject':
['maths','science'],'standard':['3','4']}
我需要核实以下事项
我试过使用下面的代码,但我被困在这里,以找出确切的方法
a={'name':['test1','test2'],'regno':['123','345'],'subject':['maths','science'],'standard':['3','4']}
lengths = [len(v) for v in a.values()]
if (len(set(lengths)) <= 1) == True:
print('All values are same')`
else:
print('All values are not same')
a={'name':['test1','test2'],'regno':['123','345'],'subject':['math','science'],'standard':['3','4']}
长度=[len(v)表示a中的v。值()
如果(len(set(length))尝试在字典项上循环,然后在值中的列表上循环:
for key, vals_list in a.items():
if len(set(vals_list)) <= 1:
print(f'{key}: All values are same!')
# Will do nothing if `vals_list` is empty
for value in vals_list:
your_other_func(value)
对于a.items()中的键、VAL\u列表:
如果len(set(vals_list))可以通过以下方式完成:
a={'name':['test1','test2'],'regno':['123','345'],'subject':
['maths','science'],'standard':['3','4']}
w = [{'name':a['name'][i], 'regno':a['regno'][i], 'standard':a['standard'][i]} for i
in range(len(a['name']))]
for x in range(len(w)):
#your_func(w[x]['name'], w[x]['reno'], w[x]['standard'])
print(w[x]['name'], w[x]['regno'], w[x]['standard'])
我会将a
重新构建为一个字典列表,然后使用dict unpacking将字典动态地分配给函数:
def func(name, regno, subject, standard):
print("name={}, regno={}, subject={}, standard={}".format(name, regno, subject, standard))
a={'name':['test1','test2'],'regno':['123','345',],'subject':
['maths','science'],'standard':['3','4']}
new_a = [dict(zip(a.keys(), x)) for x in list(zip(*a.values()))]
print(new_a)
for d in new_a:
func(**d)
输出:
[{'name': 'test1', 'regno': '123', 'subject': 'maths', 'standard': '3'}, {'name': 'test2', 'regno': '345', 'subject': 'science', 'standard': '4'}]
name='test1', regno='123', subject='maths', standard='3'
name='test2', regno='345', subject='science', standard='4'
是的,它打印“所有值都相同”,但实际上您正在测试“所有列表都具有相同的长度”。您需要什么?顺便说一下:if(len(set(length))if(len)(set(length))我需要从字典中获取值,并将其逐个传递给name='test1'regno='123'subject='math'standard='3'和name='test2'regno='345'subject='science'standard='4'列表理解w
在这里看起来很重,我建议使用显式for
循环。
[{'name': 'test1', 'regno': '123', 'subject': 'maths', 'standard': '3'}, {'name': 'test2', 'regno': '345', 'subject': 'science', 'standard': '4'}]
name='test1', regno='123', subject='maths', standard='3'
name='test2', regno='345', subject='science', standard='4'