[英]How to take space separated input in dictionary with every new input stored against a new key value?
How to create a dictionary from a string composed by space separated words with i for i in range(0, n)
as key in the dictionary ? 如何用由空格分隔的单词组成的字符串创建字典,其中i for i in range(0, n)
作为字典中的键?
Tried this: 试过这个:
i = 0
map(dic[i+=1],input().split())
It didn't work. 没用
It should output this: 它应该输出以下内容:
dic={0:'apple',1:'grapes',2:'orange',3:'banana'}
input_str = "Hello world"
result = {key: value for key, value in enumerate(input_str.split())}
print(result)
Output: 输出:
{0: 'Hello', 1: 'world'} {0:“你好”,1:“世界”}
But you can use a list
since this data structure is made for iterating over their contents and keeps order. 但是您可以使用list
因为此数据结构用于迭代其内容并保持顺序。 If you want an int as key, just use enumerate(your_list)
. 如果您想要一个int作为键,只需使用enumerate(your_list)
。
In Python, when to use a Dictionary, List or Set? 在Python中,何时使用字典,列表或集合?
You could use enumerate
: 您可以使用enumerate
:
d = {}
for i, v in enumerate(input().split()):
d[i] = v
Or simply: 或者简单地:
d = dict(enumerate(input().split()))
But why do that? 但是为什么呢? use a list
... 使用list
...
Since your keys are simply (ordered!) integers, using a dict seems an overkill as to access integer-indexed values from a list is also O(1)
. 由于您的键只是简单的(有序的!)整数,因此使用dict似乎对于从列表访问整数索引值来说也是一个过大的杀伤力,它也是O(1)
。 For example, let's look at a small comparison with the 2 versions: 例如,让我们看一下两个版本的一个小比较:
l = input().split()
d = dict(enumerate(l))
We have: 我们有:
>>> print(l)
['apple', 'orange', 'banana']
>>> print(d)
{0: 'apple', 1: 'orange', 2: 'banana'}
Now let's see how we will grab values: 现在让我们看看如何获取值:
>>> l[0]
'apple'
>>> d[0]
'apple'
>>> l[2]
'banana'
>>> d[2]
'banana'
Dictionaries have a small memory overhead and so for this case using a dictionary doesn't give any advantage. 字典的内存开销很小,因此在这种情况下使用字典不会带来任何好处。
input_ = input("enter your fruits:").split(' ')
print (dict(zip([*range(len(input_))], input_)))
# print (dict(enumerate(input_)))
output: 输出:
enter your fruits:banana kiwi orange apple
{0: 'banana', 1: 'kiwi', 2: 'orange', 3: 'apple'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.