简体   繁体   English

如何通过添加字符串和列表来创建字典。 蟒蛇

[英]how to create a dictionary by adding string and list. python

for example I have one string variable syn , and one list variable wordlist 例如我有一个字符串变量syn和一个列表变量wordlist

syn="discipline"
wordlist=[u'discipline', u'horse Riding Discipline', u'academic Discipline']

I would like to get the dictionary looks like : 我想使字典看起来像:

{ "discipline" : [u'discipline', u'horse Riding Discipline', u'academic Discipline'] }

how to do that? 怎么做?

只需直接执行以下操作即可:

mydict = {syn: wordlist}

Simply access the variables you created: 只需访问您创建的变量:

syn = "discipline"
wordlist = [u'discipline', u'horse Riding Discipline', u'academic Discipline']
result = {syn:wordlist}

If you have several of these key/value pairs, add them with standard dictionary access syntax: 如果您有几个这样的键/值对,请使用标准字典访问语法添加它们:

result = {}
data = [('dog', ['big dog', 'dogs']), ('apple', ['red apple', 'green apple'])]
for k,v in data:
    result[k] = v

Of course, if you have such a tidy object, just do result = dict(data) , but a loop as shown above can help you process your data and create a dictionary. 当然,如果您有这样一个整洁的对象,则只需执行result = dict(data) ,但是如上所示的循环可以帮助您处理数据并创建字典。 A more specific algorithm will depend on exactly what sort of code you currently have. 更具体的算法将取决于您当前拥有的代码类型。

some_dictionary = {}
some_dictionary[syn] = wordlist

Try use setdefault (built-in type) 尝试使用setdefault (内置类型)

This method returns the key value available in the dictionary and if given key is not available then it will return provided default value. 此方法返回字典中可用的键值,如果给定的键不可用,则它将返回提供的默认值。

like this 像这样

myDict =  dict()
myDict.setdefault(syn, wordlist)
print myDict

put setdefault inside your loop setdefault放入循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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