从python字典中获取值并逐个传递

2024-06-16 11:23:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面提到的字典

a={'name':['test1','test2'],'regno':['123','345'],'subject':         
  ['maths','science'],'standard':['3','4']}

我需要核实以下事项

  1. 每个值计数字典都应该匹配

  2. 一个接一个地从每个键获取值,并将其一个接一个地传递给我的另一个函数


  name = 'test1'   regno = '123'   subject='maths'   standard='3'
  name = 'test2'   regno = '345'   subject='science'   standard='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')

需要您的帮助从每个键中逐个获取值并将其传递给函数


Tags: 函数namelen字典allstandardsciencesubject
3条回答

您可以通过以下方式完成:

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'

尝试在字典项上循环,然后在值列表上循环:

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)

相关问题 更多 >