【问题标题】:How can I match & modify an array of dictionaries?如何匹配和修改字典数组?
【发布时间】:2019-11-07 21:30:31
【问题描述】:

我目前正试图匹配和修改两个字典。在较高的层次上,我有一个包含每个问题的潜在 answer_id 的字典:

[{'2194241222': 'Not at all likely - 0',
  '2194241223': '1',
  '2194241224': '2',
  '2194241391': '3',
  '2194241392': '4',
  '2194241393': '5',
  '2194241394': '6',
  '2194241395': '7',
  '2194241396': '8',
  '2194241397': '9',
  '2194241398': 'Extremely likely - 10'},
 {'2194241407': 'Very satisfied',
  '2194241408': 'Somewhat satisfied',
  '2194241409': 'Neither satisfied nor dissatisfied',
  '2194241410': 'Somewhat dissatisfied',
  '2194241411': 'Very dissatisfied'},
 {'2194241444': 'Extremely well',
  '2194241445': 'Very well',
  '2194241446': 'Somewhat well',
  '2194241447': 'Not so well',
  '2194241448': 'Not at all well'}

以及来自实际响应的一系列答案:

{'answers': [{'choice_id': '2194241397', 'row_id': '2194241221'}],
  'id': '331799110'},
 {'answers': [{'choice_id': '2194241408'}], 'id': '331799114'},
 {'answers': [{'choice_id': '2194241422'}], 'id': '331799115'},
 {'answers': [{'choice_id': '2194241445'}], 'id': '331799117'},
 {'answers': [{'choice_id': '2194241457'}], 'id': '331799122'},
 {'answers': [{'choice_id': '2194241466'}], 'id': '331799126'},
 {'answers': [{'choice_id': '2194241500'}], 'id': '331799128'},
 {'answers': [{'choice_id': '2194241535'}], 'id': '331799130'},
 {'answers': [{'choice_id': '2194241555'}], 'id': '331799132'}

如何将choice_id 数字替换为answer_id 字典的值?

所有answer_id 号码都是唯一的。

【问题讨论】:

    标签: python arrays json python-3.x dictionary


    【解决方案1】:

    我认为你可以这样做:

    # responseL - The array in the first snippet
    # answerL - The array in the second snippet
    # Convert responseL to a dictionary
    responseD = { k: v for resp_typeD in responseL for k, v in resp_typeD.items() }
    
    for answerD in answerL:
        for questionD in answerD['answers']:
            questionD['choice_id'] = responseD.get(questionD['choice_id'], "UNKNOWN")
    

    【讨论】:

    • 哇,这太棒了。这工作得很好,谢谢!我真的不明白发生了什么,但它是完美的。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    相关资源
    最近更新 更多