简体   繁体   中英

How to properly create a dictionary in Python

I am trying to create a dictionary in a function but I don't know for which reason I got this:

MONdic = {"mama"}
print MONdic

What I get as a result is :

set(['mama'])

Any help ?

dict 基于键值对(你已经创建了一个集合)

d = {'key':'val'}

dictionary must has keys and values like: my_dict = { "brand": "Ford", "model": "Mustang", "year": 1964 }

check https://www.w3schools.com/python/python_dictionaries.asp for accessing it, changing values, loop it ..

By default, if you pass an element or list of elements to {} , it will create a set .

But if you try passing key value pairs to {} , it will create a dictionary.

MONdic = {"key":"value"} , then the value of MONdic will be {"key":"value"}

But the problem is that I have a second dictionary that should merge with MONdic as in this example:

for key, value in results.items():
    MONdic[key].extend(value)

To be able to merge these two dictionaries, they need to have the same keys. The values of MONdic should be empty in the beginning and I don't want to receive these kind of results if I do so :

MONdic = {"mama":[]}
for key, value in results.items():
    MONdic[key].extend(value)

>>>> {"mama":[[1,2,5,9]]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM