Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

python - Python将新项添加到字典[重复](Python add new item to dictionary [duplicate])

This question already has an answer here:

(这个问题在这里已有答案:)

I want to add an item to an existing dictionary in python.

(我想在python中将项添加到现有字典中。)

For example, this is my dictionary:

(例如,这是我的字典:)

default_data = {
            'item1': 1,
            'item2': 2,
}

I want to add new item such that:

(我想添加新项目,以便:)

default_data = default_data + {'item3':3}

How to achieve this?

(怎么做到这一点?)

  ask by brsbilgic translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
default_data['item3'] = 3

Easy as py.

(很容易py。)

Another possible solution:

(另一种可能的方案)

default_data.update({'item3': 3})

which is nice if you want to insert multiple items at once.

(如果你想一次插入多个项目,那就太好了。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...