首页 > 解决方案 > 从结构为列表的字典中提取数据

问题描述

我的数据结构形式为 st

('["02100 - Albuquerque", "21: Mining", "2015", "1stqtr"]',
[6377340.58, 1783304.5, 124831.3, 0, 0]),

('["02200 - Los Ranchos de Albuquerque", "21: Mining", "2015", "1stqtr"]',
['*', '*', '*', '*', '*']),

('["03003 - Eddy County, Remainder", "21: Mining", "2015", "1stqtr"]',
[180120046.18, 113335033.42, 6518842.46, 0, 0]),

('["03106 - Carlsbad", "21: Mining", "2015", "1stqtr"]',
[31013031.93, 22417664.82, 1640017.58, 0, 0]),

('["02100 - Albuquerque", "21: Mining", "2015", "2ndqtr"]',
[7791546.64, 2305762.85, 161737.54, 0, 0]),

('["02200 - Los Ranchos de Albuquerque", "21: Mining", "2015", "2ndqtr"]',
['*', '*', '*', '*', '*']),

('["03003 - Eddy County, Remainder", "21: Mining", "2015", "2ndqtr"]',
[131428830.21, 78906981.18, 4529132.1, 0, 0]),

('["03106 - Carlsbad", "21: Mining", "2015", "2ndqtr"]',
[41144494.15, 28958781.08, 2158603.95, 0, 0]),

当我使用该功能时

def search_and_export(dictionary, substr):
result = []
for key in dictionary:
    if substr in key:
        result.append((key, dictionary[key]))
        print("")
        print("This is the key: " + key)
        print(“")

我出去:

This is the key: ["02100 - Albuquerque", "21: Mining", "2015", “1stqtr”] 
etc...

我想做的是定义一个函数,它允许我搜索字典并只允许我定位

('["02100 - Albuquerque”, "21: Mining”, “2015", “1stqtr"]', [6377340.58])
('["02100 - Albuquerque", "21: Mining", "2015", "2ndqtr"]’, [7791546.64])

然后将值导出到 csv 文件名分别为“02100 - Albuquerque / 21: Mining / 2015 / 1stqtr”和“02100 - Albuquerque / 21: Mining / 2015 / 2ndtqtr”

标签: python-3.xlistdictionaryexport-to-csv

解决方案


找到了解决方案。真的很简单。我为阿尔伯克基做了这个。现在只需要简单地导出到 csv 即可。

def search_and_export(dictionary):

for key, value in dictionary.items():
    if "02100 - Albuquerque" in key:
        if "21: Mining" in key:

            print("")
            print("This is the key: " + key)
            print("This is the value: " + str(value[0]))
            print("")


pprint(search_and_export(dataDict))

输出

This is the key: ["02100 - Albuquerque”, "21: Mining", "2015”, "1stqtr"]
  This is the value: 180120046.18


This is the key: ["02100 - Albuquerque”, "21: Mining", "2015", "2ndqtr"]
  This is the value: 131428830.21


This is the key: ["02100 - Albuquerque”, "21: Mining", "2015", "3rdqtr"]
  This is the value: 99306332.26


This is the key: ["02100 - Albuquerque”, "21: Mining", "2015", "4thqtr"]
  This is the value: 122534519.98

推荐阅读