将值附加到 Python 中的字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3419147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Appending values to dictionary in Python
提问by l--''''''---------''''''''''''
I have a dictionary to which I want to append to each drug, a list of numbers. Like this:
我有一本字典,我想在每个药物后面附加一个数字列表。像这样:
append(0), append(1234), append(123), etc.
def make_drug_dictionary(data):
drug_dictionary={'MORPHINE':[],
'OXYCODONE':[],
'OXYMORPHONE':[],
'METHADONE':[],
'BUPRENORPHINE':[],
'HYDROMORPHONE':[],
'CODEINE':[],
'HYDROCODONE':[]}
prev = None
for row in data:
if prev is None or prev==row[11]:
drug_dictionary.append[row[11][]
return drug_dictionary
I later want to be able to access the entirr set of entries in, for example, 'MORPHINE'.
我稍后希望能够访问 entirr 中的条目集,例如,'MORPHINE'.
- How do I append a number into the drug_dictionary?
- How do I later traverse through each entry?
- 如何在 drug_dictionary 中附加一个数字?
- 我以后如何遍历每个条目?
采纳答案by Tony Veijalainen
Just use append:
只需使用附加:
list1 = [1, 2, 3, 4, 5]
list2 = [123, 234, 456]
d = {'a': [], 'b': []}
d['a'].append(list1)
d['a'].append(list2)
print d['a']
回答by Andrew
It sounds as if you are trying to setup a list of lists as each value in the dictionary. Your initial value for each drug in the dict is []. So assuming that you have list1 that you want to append to the list for 'MORPHINE'you should do:
听起来好像您正在尝试将列表列表设置为字典中的每个值。dict 中每种药物的初始值是[]. 因此,假设您有要附加到列表中的 list1,'MORPHINE'您应该这样做:
drug_dictionary['MORPHINE'].append(list1)
You can then access the various lists in the way that you want as drug_dictionary['MORPHINE'][0]etc.
然后,您可以按照您想要的方式访问各种列表drug_dictionary['MORPHINE'][0]等。
To traverse the lists stored against key you would do:
要遍历针对键存储的列表,您可以执行以下操作:
for listx in drug_dictionary['MORPHINE'] :
do stuff on listx
回答by Jason Orendorff
To append entries to the table:
将条目附加到表中:
for row in data:
name = ??? # figure out the name of the drug
number = ??? # figure out the number you want to append
drug_dictionary[name].append(number)
To loop through the data:
遍历数据:
for name, numbers in drug_dictionary.items():
print name, numbers
回答by Piotr Czapla
You should use append to add to the list. But also here are few code tips:
您应该使用 append 添加到列表中。但这里还有一些代码提示:
I would use dict.setdefaultor defaultdictto avoid having to specify the empty list in the dictionary definition.
我会使用dict.setdefaultordefaultdict避免在字典定义中指定空列表。
If you use prevto to filter out duplicated values you can simplfy the code using groupbyfrom itertoolsYour code with the amendments looks as follows:
如果您使用prevto 过滤掉重复值,您可以使用groupby来自itertools您的代码的修改来简化代码,如下所示:
import itertools
def make_drug_dictionary(data):
drug_dictionary = {}
for key, row in itertools.groupby(data, lambda x: x[11]):
drug_dictionary.setdefault(key,[]).append(row[?])
return drug_dictionary
If you don't know how groupby works just check this example:
如果您不知道 groupby 的工作原理,请查看以下示例:
>>> list(key for key, val in itertools.groupby('aaabbccddeefaa'))
['a', 'b', 'c', 'd', 'e', 'f', 'a']
回答by George Lambert
how do i append a number into the drug_dictionary?
我如何在 drug_dictionary 中附加一个数字?
Do you wish to add "a number" or a set of values?
您想添加“一个数字”还是一组值?
I use dictionaries to build associative arrays and lookup tables quite a bit.
我经常使用字典来构建关联数组和查找表。
Since python is so good at handling strings, I often use a string and add the values into a dict as a comma separated string
由于python非常擅长处理字符串,我经常使用字符串并将值作为逗号分隔的字符串添加到字典中
drug_dictionary = {}
drug_dictionary={'MORPHINE':'',
'OXYCODONE':'',
'OXYMORPHONE':'',
'METHADONE':'',
'BUPRENORPHINE':'',
'HYDROMORPHONE':'',
'CODEINE':'',
'HYDROCODONE':''}
drug_to_update = 'MORPHINE'
try:
oldvalue = drug_dictionary[drug_to_update]
except:
oldvalue = ''
# to increment a value
try:
newval = int(oldval)
newval += 1
except:
newval = 1
drug_dictionary[drug_to_update] = "%s" % newval
# to append a value
try:
newval = int(oldval)
newval += 1
except:
newval = 1
drug_dictionary[drug_to_update] = "%s,%s" % (oldval,newval)
The Append method allows for storing a list of values but leaves you will a trailing comma
Append 方法允许存储值列表,但会留下一个尾随逗号
which you can remove with
你可以删除
drug_dictionary[drug_to_update][:-1]
the result of the appending the values as a string means that you can append lists of values as you need too and
将值作为字符串附加的结果意味着您也可以根据需要附加值列表,并且
print "'%s':'%s'" % ( drug_to_update, drug_dictionary[drug_to_update])
can return
可以返回
'MORPHINE':'10,5,7,42,12,'
回答by Gunjan Thareja
vowels = ("a","e","i","o","u") #create a list of vowels
my_str = ("this is my dog and a cat") # sample string to get the vowel count
count = {}.fromkeys(vowels,0) #create dict initializing the count to each vowel to 0
for char in my_str :
if char in count:
count[char] += 1
print(count)
回答by VahidG
If you want to append to the lists of each key inside a dictionary, you can append new values to them using +operator (tested in Python 3.7):
如果要附加到字典中每个键的列表,可以使用+运算符向它们附加新值(在 Python 3.7 中测试):
mydict = {'a':[], 'b':[]}
print(mydict)
mydict['a'] += [1,3]
mydict['b'] += [4,6]
print(mydict)
mydict['a'] += [2,8]
print(mydict)
and the output:
和输出:
{'a': [], 'b': []}
{'a': [1, 3], 'b': [4, 6]}
{'a': [1, 3, 2, 8], 'b': [4, 6]}
mydict['a'].extend([1,3])will do the job same as +without creating a new list (efficient way).
mydict['a'].extend([1,3])将完成与+不创建新列表相同的工作(有效方式)。

