简体   繁体   English

Python-如何访问字典中由用户输入添加的值?

[英]Python - how to access values in dictionary that were added by user input?

Say I have an empty dictionary that a user adds an arbitrary number of items into. 假设我有一个空字典,用户可以在其中添加任意数量的项目。 After the user adds items to the dictionary, I want to then loop through that dictionary and be able to pull values out of it. 用户将项目添加到字典后,我想遍历该字典并能够从中提取值。 What is the best way to access the items in the dictionary since I don't know the name of the key? 由于我不知道键名,访问字典中各项的最佳方法是什么?

For example say I have the following: 例如说我有以下内容:

# my shopping cart that starts off empty
shopping_cart = {}

# user enters how many items they will have in the cart total
total_items = input("How many items will you add to your cart? ")

# User adds both the value and the key of each item to add
for i in total_items:
    name = input("Enter name of item to add: ")
    location = input("Is the item in front, middle, or back of cart? ")

    shopping_cart[name] = location

At this point I have a shopping_cart dictionary, but I don't have a way to know what the KEYs or VALUEs are. 此时,我有一个shopping_cart字典,但是我没有办法知道键或值是什么。

..... Now say there is some large string of thousands of characters in random order called random_string . .....现在说一下,有一个随机的大字符串,包含数千个字符,称为random_string It looks like "axdfebzsdcdsl apple fjdkslaz pair ....." Notice how the string is random, but periodically there are names of items like "apple" and "pair". 它看起来像“ axdfebzsdcdsl apple fjdkslaz ……。”请注意,字符串是随机的,但是定期会有诸如“ apple”和“ pair”之类的项目名称。

What I want to do is loop my shopping_cart dictionary and find the next index position within my random_string where the item in my shopping_cart appears. 我想要做的是循环我shopping_cart字典,找到我在接下来的索引位置random_string凡在我的项目shopping_cart出现。

For example - let's say the user adds 3 items to the shopping cart. 例如,假设用户将3个商品添加到购物车中。 The items are "donkey", "apple", "pair". 这些项目是“驴”,“苹果”,“对”。

What I want to do is read through the random_string in order, and return the dictionary value that appears next in the string. 我想做的是依次读取random_string并返回出现在字符串中的字典值。 IE in this case, "apple" is the next item in the random string, so it should be returned so I can lookup the value of "apple" in the dictionary and get the location of the item. IE在这种情况下,“苹果”是随机字符串中的下一个项目,因此应返回它,以便我可以在字典中查找“苹果”的值并获取该项目的位置。

I have working code to do everything that is necessary EXCEPT for knowing how to pull the Keys out of the dictionary. 我有工作代码来执行所有必要的工作,除了知道如何从字典中拉出键外。 I've copied a line below that essentially shows what I'm trying to accomplish. 我在下面复制了一行,该行基本上显示了我要完成的工作。 The problem is I don't know what DICT_KEY is, because it was added by the user. 问题是我不知道DICT_KEY是什么,因为它是由用户添加的。

index = random_string.find([DICT_KEY], index)

........ Not to confuse things, but I'm considering making an empty list that mirrors the dictionary values. ........请勿混淆,但我正在考虑制作一个反映字典值的空列表。 In other words, when the user adds the item "apple" to the dictionary, I could add it to the dictionary and to the list. 换句话说,当用户将“苹果”项添加到字典中时,我可以将其添加到字典和列表中。 That way I can lookup the item in the dictionary by using it's index position in the list. 这样,我可以通过使用列表中的索引位置在字典中查找该项目。 seems like a bad way to handle this though, so happy to get any advice you can offer... 不过,这似乎是一种不好的处理方式,很高兴获得您可以提供的任何建议...

As you can see, I'm new at this! 如您所见,我是新手!

>>> a={'apple':'front','donkey':'middle','pair':'back'}
>>> s='asdfhskdfksjdf;ksjapplefsakdjfskdjfapplesdfksdjdonkeydlkfjsldjfdpair'
>>> {k:[m.start() for m in re.finditer(k,s)] for k in a}
{'pair': [64], 'donkey': [47], 'apple': [18, 35]}

This one found two apple , one donkey and one pair in the string at indices 18 / 35 / 47 / 64 . 这一发现了两个apple ,一个donkey和一个pair在索引字符串中18 / 35 / 47 / 64


Explanation 说明
Follow up on the commands used earlier 跟进先前使用的命令

Create a new dictionary with the keys I have and assign a constant value. 用我拥有的keys创建一个新字典并分配一个常数。

>>> a
{'pair': 'back', 'donkey': 'middle', 'apple': 'front'}
>>> {k:0 for k in a}
{'pair': 0, 'donkey': 0, 'apple': 0}

That allows us to make a dictionary with each key having same value 0 . 这使我们可以创建一个字典,每个键的值都为0 a being the dictionary you already made. a您已经制作的字典。

Now let's see how we set the values to indices of these words in the big string. 现在让我们看看如何将值设置为大字符串中这些单词的索引。

>>> [m.start() for m in re.finditer('apple',s)]
[18, 35]

re.finditer returns as many matches in s for apple . re.finditer返回sapple匹配的匹配项。
For each match m thus found, m.start() returns the start index of the match. 对于找到的每个匹配mm.start()返回匹配的起始索引。
Now this gives a list of indices where apple is appearing in the string. 现在,这给出了一个字符串列表中出现苹果的索引列表。

Finally if we combine the above two we get a dictionary with our original keys. 最后,如果我们将以上两个结合起来,我们将得到带有原始键的字典。 And values as a list of indices where they appear in the string. 和值作为它们在字符串中出现的索引的列表。

>>> {k:[m.start() for m in re.finditer(k,s)] for k in a}
{'pair': [64], 'donkey': [47], 'apple': [18, 35]}

UPDATE2 UPDATE2
After new req. 新要求后。 in comments 在评论中

>>> d={k:[m.start() for m in re.finditer(k,s)] for k in a}
>>> from collections import defaultdict
>>> nd=defaultdict(list)
>>> for k in d:
...   nd[a[k]].extend(d[k])
... 
>>> dict(nd)
{'front': [18, 35], 'middle': [47], 'back': [64]}

If you do not want to go twice over then.. 如果您不想重复两次,那么..

>>> from collections import defaultdict
>>> nd=defaultdict(list)
>>> for k in a:
...   for m in re.finditer(k,s):
...     nd[a[k]].append(m.start())
... 
>>> dict(nd)
{'front': [18, 35], 'middle': [47], 'back': [64]}

UPDATE3 UPDATE3

>>> {(k,a[k]):[m.start() for m in re.finditer(k,s)] for k in a}
{('pair', 'back'): [64], ('apple', 'front'): [18, 35], ('donkey', 'middle'): [47]}
>>> {m.start():(k,a[k]) for k in a for m in re.finditer(k,s)}
{64: ('pair', 'back'), 18: ('apple', 'front'), 35: ('apple', 'front'), 47: ('donkey', 'middle')}

UPDATED 更新

If indices are more important for you then do the below 如果索引对您来说更重要,请执行以下操作

>>> {m.start():k  for k in a for m in re.finditer(k,s)}
{64: 'pair', 18: 'apple', 35: 'apple', 47: 'donkey'}

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

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