追加只适用于list
,因此您不能在dict
中使用它,因为它在作业中存储了string
。所以,你可以通过两种方式来完成。使用list
来存储值,然后使用append
it或add
到string
本身。
使用list
:
dic_loc = {'latitude': ['Value for latitude '], 'longitude': ['Value for longitude'], 'timestamp': ['Time Stamp']}
def make_timestamped_loc(La, Lng, Time):
dic_loc['latitude'].append(La)
dic_loc['longitude'].append(Lng)
dic_loc['timestamp'].append(Time)
make_timestamped_loc(37.481236, 126.952733, 1483196400)
make_timestamped_loc(37.481126, 126.952733, 1498859012)
print(dic_loc)
'''
{
'latitude': ['Value for latitude ', 37.481236, 37.481126],
'longitude': ['Value for longitude', 126.952733, 126.952733],
'timestamp': ['Time Stamp', 1483196400, 1498859012]
}
'''
或者strings
:
dic_loc = {'latitude': 'Value for latitude ', 'longitude': 'Value for longitude', 'timestamp': 'Time Stamp'}
def make_timestamped_loc(La, Lng, Time):
dic_loc['latitude']+= ' '+str(La)
dic_loc['longitude']+=' '+str(Lng)
dic_loc['timestamp']+=' '+str(Time)
make_timestamped_loc(37.481236, 126.952733, 1483196400)
make_timestamped_loc(37.481126, 126.952733, 1498859012)
print(dic_loc)
'''
{
'latitude': 'Value for latitude 37.481236 37.481126',
'longitude': 'Value for longitude 126.952733 126.952733',
'timestamp': 'Time Stamp 1483196400 1498859012'}
'''
如果你正在寻找的只是:
如果可以,我想消除已有的str值并将新值添加到每个键。
您可以直接赋值:
def make_timestamped_loc(La, Lng, Time):
dic_loc['latitude'] = La
dic_loc['longitude'] = Lng
dic_loc['timestamp'] = Time
如果您甚至没有指定输出应该是什么样子,您如何期望得到正确答案? –