环境是Python 2.7,外部库向后移植csv模块。
所以我有一个包含信息的csv文件,我正尝试将其加载为非常特定的格式,以便于访问。
现在所需的格式是:
“主”键是城市名称,然后具有两个嵌套的字典元素。一个用于凭证(用户名和密码,均为密钥),最后一个用于列表,其中添加了属于该城市的每个列表。因此,如下面的屏幕截图所示,某些城市的列表将比其他城市更多。
我的代码尝试尝试实现以下目标:
from backports import csv
import json
import string
import datetime
import hmac
import base64
import hashlib
import requests
import pprint
import time
from io import open
import sys
reload(sys)
sys.setdefaultencoding('utf8')
from urllib2 import urlopen
import urllib
def get_data(file_name):
header_list = ""
with open(file_name, 'r') as f:
reader = csv.reader(f)
try:
# Python 2's next call
header_list = reader.next()
except AttributeError:
# Python 3.0 and later
header_list = next(reader)
data = [row for row in reader]
return data
csv_file = "mapping.csv"
csv_data = get_data(csv_file)
print(len(csv_data))
credentials = dict()
cities = dict()
for x in csv_data:
lists = dict()
credentials.update([('username', str(x[2])), ('password', str(x[3]))])
list_name = x[0]
list_id = x[4]
try:
lists = cities[key]['lists']
except:
pass
lists[list_name] = list_id
key = x[1]
value = {'credentials': credentials, 'lists': lists}
cities.update([(key, value)])
print("")
print(cities)
问题: 我为此很难过,因为它会将所有list_names添加到每个city_id中,无论它是否适用于该列表。任何帮助,将不胜感激。我正在不确定我为什么要做的事情有缺陷。谢谢。
当前结果:
newyork
{'credentials': {'username': 'exotic', 'password': 'abc123'}, 'lists': {u'a': u'9', u'c': u'8', u'b': u'10'}}
miami
{'credentials': {'username': 'exotic', 'password': 'abc123'}, 'lists': {u'a': u'9', u'c': u'8', u'b': u'10'}}
washington
{'credentials': {'username': 'exotic', 'password': 'abc123'}, 'lists': {u'a': u'9', u'c': u'8', u'b': u'10'}}
detroit
{'credentials': {'username': 'exotic', 'password': 'abc123'}, 'lists': {u'a': u'9', u'c': u'8', u'b': u'10'}}
答案 0 :(得分:0)
所以我意识到自己的错误,再次解决了。我在循环内部进行分配完全错误。对于任何对此感兴趣的人,都是正确的代码。
for x in csv_data:
city = x[1]
try:
mycity = cities[city]
except:
cities[city] = {}
try:
lists = cities[city]['lists']
except:
cities[city]['lists'] = {}
list_name = x[0]
list_id = x[4]
cities[city]['lists'][list_name] = list_id
try:
credentials = cities[city]['credentials']
except:
cities[city]['credentials'] = {}
username = x[2]
password = x[3]
cities[city]['credentials']['username'] = username
cities[city]['credentials']['password'] = password
基本上,我必须检查密钥是否已经存在,如果不存在,则需要创建它并为其分配一个空值。