我一直试图用户的美丽汤解析一个网站,并获得必要的数据。现在我有了数据,我想用熊猫来组织数据,但为此,我想制作一本结构良好的字典。
我清理过的数据在字典data_dict中。这里,键是海龟的名字,值是有关海龟的一些信息。
data_dict = {'Aesop': ['AGE: 7 Years Old', 'WEIGHT: 6 lbs', 'SEX: Female', 'BREED: African Aquatic Sideneck Turtle', 'SOURCE: found in Lake Erie'], 'Caesar': ['AGE: 2 Years Old', 'WEIGHT: 4 lbs', 'SEX: Male', 'BREED: Greek Tortoise', 'SOURCE: hatched in house'], 'Sulla': ['AGE: 1 Year Old', 'WEIGHT: 1 lb', 'SEX: Male', 'BREED: African Aquatic Sideneck Turtle', 'SOURCE: found in Lake Erie']}现在,我希望这本字典的键类似于"turtle_1“和下一个"turtle_2”等等。所以我写了代码:
name_num = 1
for name in list(data_dict.keys()):
data_dict["turtle_"+str(name_num)] = data_dict.pop(name)
name_num += 1这改变了"Aesop"的钥匙..。(等等)到"turtle_1"..。诸若此类。现在,我希望海龟的名字(以前是键)是相应键的值。我希望data_dict看起来像这样:
data_dict = {'turtle_1': ['AGE: 7 Years Old', 'WEIGHT: 6 lbs', 'SEX: Female', 'BREED: African Aquatic Sideneck Turtle', 'SOURCE: found in Lake Erie', 'NAME: Aesop'], 'turtle_2': ['AGE: 2 Years Old', 'WEIGHT: 4 lbs', 'SEX: Male', 'BREED: Greek Tortoise', 'SOURCE: hatched in house', 'NAME: Caesar'], 'turtle_3': ['AGE: 1 Year Old', 'WEIGHT: 1 lb', 'SEX: Male', 'BREED: African Aquatic Sideneck Turtle', 'SOURCE: found in Lake Erie', 'NAME: Sulla']}因此,键得到一个新的值,这是每个海龟的名字。谢谢,我非常感谢你的帮助。
发布于 2019-07-30 13:39:19
附加姓名:
data_dict = {'Aesop': ['AGE: 7 Years Old', 'WEIGHT: 6 lbs', 'SEX: Female', 'BREED: African Aquatic Sideneck Turtle', 'SOURCE: found in Lake Erie'], 'Caesar': ['AGE: 2 Years Old', 'WEIGHT: 4 lbs',
'SEX: Male', 'BREED: Greek Tortoise', 'SOURCE: hatched in house'], 'Sulla': ['AGE: 1 Year Old', 'WEIGHT: 1 lb', 'SEX: Male', 'BREED: African Aquatic Sideneck Turtle', 'SOURCE: found in Lake Erie']}
name_num = 1
for name in list(data_dict.keys()):
data_dict["turtle_"+str(name_num)] = data_dict.pop(name)
data_dict["turtle_"+str(name_num)].append('NAME: '+name)
name_num += 1
print(data_dict)发布于 2019-07-30 13:40:28
key_map = {}
for i,k in enumerate(data_dict.keys()):
key_map['turtle_'+str(i+1)] = k # store reverse map from turtle_1 -> name1
data_dict['turtle_'+str(i+1)] = data_dict.pop(k)turtle_1访问哪个海龟对应于key_map。>>> key_map
{'turtle_1': 'Aesop', 'turtle_2': 'Caesar', 'turtle_3': 'Sulla'}发布于 2019-07-30 13:41:37
就地:只是将另一个元素添加到与键(或名称)对应的列表中。
key_count = 1
for name in list(data_dict.keys()):
newlist = data_dict.pop(name)
newlist.append('NAME : ' + name)
data_dict['turtle_' + str(key_count)] = newlist
key_count = key_count +1https://stackoverflow.com/questions/57273026
复制相似问题