用一个键值和没有对应的值在python中初始化一个字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20079681/
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
Initializing a dictionary in python with a key value and no corresponding values
提问by user2989027
I was wondering if there was a way to initialize a dictionary in python with keys but no corresponding values until I set them. Such as:
我想知道是否有办法在 python 中用键初始化字典,但在我设置它们之前没有相应的值。如:
Definition = {'apple': , 'ball': }
and then later i can set them:
然后我可以设置它们:
Definition[key] = something
I only want to initialize keys but I don't know the corresponding values until I have to set them later. Basically I know what keys I want to add the values as they are found. Thanks.
我只想初始化键,但我不知道相应的值,直到我以后必须设置它们。基本上我知道我想在找到值时添加哪些键。谢谢。
采纳答案by Scott Hunter
You could initialize them to None.
您可以将它们初始化为None.
回答by Hammer
you could use a defaultdict. It will let you set dictionary values without worrying if the key already exists. If you access a key that has not been initialized yet it will return a value you specify (in the below example it will return None)
你可以使用 defaultdict。它会让你设置字典值而不必担心键是否已经存在。如果您访问尚未初始化的键,它将返回您指定的值(在下面的示例中,它将返回 None)
from collections import defaultdict
your_dict = defaultdict(lambda : None)
回答by codegeek
Use the fromkeysfunction to initialize a dictionary with any default value. In your case, you will initialize with Nonesince you don't have a default value in mind.
使用该fromkeys函数用任何默认值初始化字典。在您的情况下,您将初始化为,None因为您没有考虑默认值。
empty_dict = dict.fromkeys(['apple','ball'])
this will initialize empty_dictas:
这将初始化empty_dict为:
empty_dict = {'apple': None, 'ball': None}
As an alternative, if you wanted to initialize the dictionary with some default value other than None, you can do:
作为替代方案,如果您想使用除 之外的其他默认值来初始化字典None,您可以执行以下操作:
default_value = 'xyz'
nonempty_dict = dict.fromkeys(['apple','ball'],default_value)
回答by creggnog
You can initialize the values as empty strings and fill them in later as they are found.
您可以将这些值初始化为空字符串,然后在找到它们时填充它们。
dictionary = {'one':'','two':''}
dictionary['one']=1
dictionary['two']=2
回答by Robert Lugg
Based on the clarifying comment by @user2989027, I think a good solution is the following:
根据@user2989027 的澄清评论,我认为一个好的解决方案如下:
definition = ['apple', 'ball']
data = {'orange':1, 'pear':2, 'apple':3, 'ball':4}
my_data = {}
for k in definition:
try:
my_data[k]=data[k]
except KeyError:
pass
print my_data
I tried not to do anything fancy here. I setup my data and an empty dictionary. I then loop through a list of strings that represent potential keys in my data dictionary. I copy each value from data to my_data, but consider the case where data may not have the key that I want.
我尽量不在这里做任何花哨的事情。我设置了我的数据和一个空字典。然后我循环遍历表示数据字典中潜在键的字符串列表。我将数据中的每个值复制到 my_data,但请考虑数据可能没有我想要的键的情况。
回答by Robert Lugg
It would be good to know what your purpose is, why you want to initialize the keys in the first place. I am not sure you need to do that at all.
最好知道您的目的是什么,为什么要首先初始化密钥。我不确定你是否需要这样做。
1) If you want to count the number of occurrences of keys, you can just do:
1)如果你想计算键出现的次数,你可以这样做:
Definition = {}
# ...
Definition[key] = Definition.get(key, 0) + 1
2) If you want to get None (or some other value) later for keys that you did not encounter, again you can just use the get() method:
2)如果您想稍后为您没有遇到的键获取 None (或其他值),您可以再次使用 get() 方法:
Definition.get(key) # returns None if key not stored
Definition.get(key, default_other_than_none)
3) For all other purposes, you can just use a list of the expected keys, and check if the keys found later match those.
3)出于所有其他目的,您可以只使用预期键的列表,并检查稍后找到的键是否与这些键匹配。
For example, if you only want to store values for those keys:
例如,如果您只想存储这些键的值:
expected_keys = ['apple', 'banana']
# ...
if key_found in expected_keys:
Definition[key_found] = value
Or if you want to make sure all expected keys were found:
或者,如果您想确保找到所有预期的键:
assert(all(key in Definition for key in expected_keys))
回答by Aktufono
q = input("Apple")
w = input("Ball")
Definition = {'apple': q, 'ball': w}

