【问题标题】:How to get values of one key from multiple dictionaries in python?如何从python中的多个字典中获取一个键的值?
【发布时间】:2016-05-05 05:26:44
【问题描述】:

这是我在data.txt 文件中的数据

{"setup": "test", "punchline": "ok", "numOfRatings": 0, "sumOfRatings": 0},
{"setup": "test2", "punchline": "ok2", "numOfRatings": 0, "sumOfRatings": 0}

我怎样才能只从每个setup 中获取数据? 使用循环的字典?

谢谢

【问题讨论】:

  • 你试过了吗?
  • 这个数据是 JSON 格式的吗?它看起来像。如果是这样,您是否尝试过使用json 模块?如果它不起作用,那么错误消息或问题是什么?展示您迄今为止的尝试有助于读者了解您需要什么样的指导。

标签: python loops dictionary


【解决方案1】:

我不确定您是如何将字典放入文本文件的,但如果可以删除尾随逗号,即

{"setup": "test", "punchline": "ok", "numOfRatings": 0, "sumOfRatings": 0}
{"setup": "test2", "punchline": "ok2", "numOfRatings": 0, "sumOfRatings": 0}

这样的事情可能对你有用:

def dicts_from_file(file):
    dicts_from_file = []
    with open(file,'r') as inf:
        for line in inf:
            dicts_from_file.append(eval(line))
    return dicts_from_file

def get_setups(dicts):
    setups = []
    for dict in dicts:
        for key in dict:
            if key == "setup":
                setups.append(dict[key])
    return setups

print get_setups(dicts_from_file("data.txt"))

【讨论】:

    【解决方案2】:
        f = open('data')
        for line in f:
            d = ast.literal_eval(line)[0]
            print d['setup']
    

    对于此代码,您需要在每一行之后添加“,”,因为 ast.literal_eval(line) 将行转换为元组。

    如果你在每个 dict 之后没有 ',' 然后使用这个

    f = open('data')
    for line in f:
       d = ast.literal_eval(line)
       print d['setup']
    

    【讨论】:

      【解决方案3】:

      如果你的文件中的行是标准的dict字符串,你可以试试这个。

      def get_setup_from_file(file_name):
          result = []
          f = open(file_name, "r")
          for line in f.xreadlines():
              # or  line_dict = json.loads(line)
              line_dict = eval(line)  # if line end witch ',', try eval(line[0:-1])
              result.append(line_dict["setup"])
          return result
      

      希望这对您有所帮助。

      【讨论】:

        【解决方案4】:

        如果是标准的dict字符串,试试这个:

        with open(file,'r') as file_input:
            for line in file_input:
                print eval(line).get("setup")
        

        【讨论】:

          猜你喜欢
          • 2015-03-18
          • 2018-12-03
          • 2014-03-22
          • 1970-01-01
          • 1970-01-01
          • 2021-01-23
          • 1970-01-01
          • 2022-12-05
          • 2016-01-19
          相关资源
          最近更新 更多