Home > Net >  add value to dictionary key as list
add value to dictionary key as list

Time:02-24

Is it possible I can treat my dictionary's key's values as list?

How to append new value to that list?

#my dictionary
mydic = {}

#my key
username = "praveen"

#my value
user_accessKey = "tmp1"
user_accessKey2 = "tmp2"

How to construct a dictionary like this, with my key and value?

print (mydic)
{"praveen":["tmp1","tmp2"]}

CodePudding user response:

Simple dictionary assignment

mydic[username] = [user_accessKey, user_accessKey2]

To append values (thanks @wjandrea for the suggestion):

mydic.setdefault(username, []).append(new_value)

CodePudding user response:

The simplest would be to do it directly:

mydic = {username: [user_accessKey, user_accessKy2]}
  • Related