簡體   English   中英

在字典中訪問元組值

[英]Accessing tuple values in a dict

q = "cats dogs"

d = {'cats': {1: 1, 2: 3, 3: 1, 4: 1}, 'nuts': {3: 1}, 'egg': {5: 1, 6: 2}, 'dogs': {1: 8, 2: 2, 3: 4}, 'idea': {4: 1}, 'frog': {2: 1, 4: 1, 5: 1}}

newList = []

for word in q:
   for x,y in d.values():
       newList.append(d[word].x())

我在這里嘗試做的是獲取數字對的每個第一部分,並將其與q中的一個單詞對應時放入列表中。 所以我期望newList是[1,2,3,4,1,2,3]。

我收到ValueError:太多值無法解包(預期2)。 我應該怎么做?

字典“ d”中的值實際上是字典本身,而不是元組。 我認為您可能需要重新組織一下。

for word in q.split(" "):
  if word in d:
    child_dict = d[word]
    for key in child_dict:
      newList.append(key)

這是您要找的東西嗎?

q = "cats dogs"

d = {'cats': {1: 1, 2: 3, 3: 1, 4: 1}, 'nuts': {3: 1}, 'egg': {5: 1, 6: 2}, 'dogs': {1: 8, 2: 2, 3: 4}, 'idea': {4: 1}, 'frog': {2: 1, 4: 1, 5: 1}}

newList = []

for word in q.split(' '):
    newList.extend(list(d[word].keys()))

print(newList)

打印[1, 2, 3, 4, 1, 2, 3]

q = "cats dogs"

d = {'cats': {1: 1, 2: 3, 3: 1, 4: 1}, 'nuts': {3: 1}, 'egg': {5: 1, 6: 2}, 'dogs': {1: 8, 2: 2, 3: 4}, 'idea': {4: 1}, 'frog': {2: 1, 4: 1, 5: 1}}

newList = []    

for word in q.split(' '):
    if word in d:
        newList.extend([i for i in d[word]])

print(newList)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM