开发者

python: adding to a dict gives error

开发者 https://www.devze.com 2023-04-10 21:10 出处:网络
playlist = {} playlist.update(position, title) here position and title are two strings. I am getting the following开发者_JS百科 error:
playlist = {}
playlist.update(position, title)

here position and title are two strings. I am getting the following开发者_JS百科 error: TypeError: update expected at most 1 arguments, got 2

could some please help? thanks


You can only update a dict with another dictionnary (you could also give it an iterable of tuples (key, value) :

playlist = {item1 : value1}
playlist.update({position : title})
print playlist

>>> {item1 : value1, position : title}

playlist.update([(item2, value2),])
print playlist
>>> {item1 : value1, position : title, item2: value2}


dict.update() expects a dictionary:

playlist = {}
playlist.update({position: title})

If you just want to set a single key, don't use update - use bracket notation instead:

playlist[position] = title


You must pass a dict as argument:

>>> a = {}
>>> a.update({'a': 1})
>>> a
{'a': 1}


playlist[position] = title

This is the way you should do this. Update is handy when you try to copy elements of one dict into another one.


Use this:

playlist[position] = title

playlist.update is to be used with a dictionary as an argument:

playlist.update({position: title})


You have already got the answer. Posting a few good links:

http://docs.python.org/library/stdtypes.html#dict.update

python dictionary update method

http://www.tutorialspoint.com/python/dictionary_update.htm

0

精彩评论

暂无评论...
验证码 换一张
取 消