【问题标题】:How to fetch key, value pairs of a dictionary encapsulated inside a string? [closed]如何获取封装在字符串中的字典的键值对? [关闭]
【发布时间】:2020-07-02 10:38:13
【问题描述】:

在 Python 文件中,编写一个程序以对包含数据键的路由执行 GET 请求,值是包含以下格式的项目的字符串:key=STRING,age=INTEGER。这里需要统计存在多少个年龄等于或大于50的物品,并打印出这个最终值。

示例输入 {"数据":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"}

示例输出 2

【问题讨论】:

    标签: python python-3.x django flask


    【解决方案1】:

    您可能知道json 中给出了数据格式。所以首先我们想把数据解析成一个普通的python字典

    import json
    output = YOUR_GET_STATEMENT
    output_dict = json.loads(output)
    

    现在你有一个普通的 python 字典,它有一个给定的字符串("key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47") 作为键值“data ”。 您现在可以使用简单的字符串操作来过滤您的数据。

    # count the occurences of age > 50
    count = 0
    values = output_dict['data'].replace(' ','').split(',')
    for value in values:
        if not 'age' in value:
            continue
        age = int(value.split('=')[1])
        if age > 50:
            count += 1
    print(count)
    

    【讨论】:

      【解决方案2】:

      您是否尝试过使用split 函数?您可以用“,”分割初始字符串,并循环遍历结果数组的每个项目。在循环中,您再次按“=”拆分,这将为您提供一个新数组(我们称之为item_parts)。当item_parts[0] 等于"age" 时,检查item_parts[1] >= 50

      total = 0
      initial_value = "key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"
      for item in initial_value.split(","):
          item_parts = item.strip().split("=")  # strip removes any space
          if item_parts[0] == "age" and int(item_parts[1]) >= 50:
              total = total + 1
      print(total)
      

      【讨论】:

        【解决方案3】:

        代码:

        data={"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"}
        count=0
        for i,value in enumerate(data["data"].split(","),0):
            if(i%2==1) and int(value.strip()[4:])>=50:
                count+=1
        print(count)
        

        输出:

        2
        

        【讨论】:

        • 如果您满意,请接受答案。谢谢。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-20
        • 2016-12-16
        • 2012-05-09
        • 2021-01-31
        • 2021-10-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多