【问题标题】:How do I create multiple keys from a list with each key assigned to a unique array?如何从列表中创建多个键,每个键分配给一个唯一的数组?
【发布时间】:2020-08-11 17:13:58
【问题描述】:

我的目标是用 Python 构建一个字典。我的代码似乎有效。但是,当我尝试将值附加到单个键时,该值会附加到多个键。我理解这是因为 fromkeys 方法将多个键分配给同一个列表。如何从一个列表中创建多个键,每个键都分配给一个唯一的数组?

#Create an Array with future dictionary keys
x = ('key1', 'key2', 'key3')

#Create a Dictionary from the array

myDict = dict.fromkeys(x,[])

#Add some new Dictionary Keys
myDict['TOTAL'] = []

myDict['EVENT'] = []



#add an element to the Dictionary works as expected

myDict['TOTAL'].append('TOTAL')

print(myDict)

#{'key1': [], 'key2': [], 'key3': [], 'TOTAL': ['TOTAL'], 'EVENT': []}



#add another element to the Dictionary
#appending data to a key from the x Array sees the data appended to all the keys from the x array
myDict['key1'].append('Entry')

print(myDict)

#{'key1': ['Entry'], 'key2': ['Entry'], 'key3': ['Entry'], 'TOTAL': ['TOTAL'], 'EVENT':
# []}

【问题讨论】:

  • 您混淆了参考和价值。这些字典键中的每一个都指向 same 列表。 myDict = dict.fromkeys([(key, []) for key in x])
  • 这能回答你的问题吗? Python -- by value vs by reference
  • 我明白你在说什么,我很感激。如何创建我的字典,使每个键都指向一个唯一的列表?

标签: python


【解决方案1】:

Key1、key2 和 key3 都包含对您要附加到的单个列表的引用。它们并不都包含一个唯一的列表。

Jared 上面的回答是正确的。你也可以写:

myDict = dict()
for key in x:
  myDict[key] = []

做同样的事情。

【讨论】:

  • 我想你有它。我将如何创建字典以便每个键都引用一个唯一的列表?
  • @MatthewDavidJankowski 查看我对您问题的评论。
  • 是的,Jared Smith 首先回答了这个问题。如果你是新手(像我一样),列表推导可能很难解析。我将使用“长”版本编辑我的答案。
  • 将稍等片刻,看看是否有人有更优雅的方式来做我需要做的事情。如果没有人回复,我会接受这个作为答案。你的回答对我帮助很大。谢谢!
  • 在下面的答案中,您不需要 tempdict 步骤。您不必使用 fromkeys 创建字典。您可以使用字符串分配一个键。 myDict['key1'] = [] 将创建该键并为其分配一个空列表作为值。另外,我不能从你的问题中完全看出,但你知道你不必在字典值中有一个列表,对吧? myDict['total'] = 1000 也可以。当然,如果您知道这一点,但只是希望嵌套列表中的所有内容用于此用途,请随意忽略。
【解决方案2】:

根据迄今为止的答案,我拼凑出一种可行的方法。这是执行此操作的“python”还是“python 最佳”方式?

#Create an Array with future dictionary keys
x = ('key1', 'key2', 'key3')


#Create a Dictionary from the array

tempDict = dict.fromkeys(x,[])


myDict = {}



for key in tempDict.keys():
    
    print(key)
    
    myDict[key] = []


#Add some new Dictionary Keys

myDict['TOTAL'] = []

myDict['EVENT'] = []

print(myDict)


#add an element to the Dictionary works as expected   
myDict['TOTAL'].append('TOTAL')
print(myDict)
#{'key1': [], 'key2': [], 'key3': [], 'TOTAL': ['TOTAL'], 'EVENT': []}



#add another element to the Dictionary
#appending data to a key from the x  Array sees the data appended to all the x keys.
myDict['key1'].append('Entry') 
print(myDict)

#{'key1': ['Entry'], 'key2': [], 'key3': [], 'TOTAL': ['TOTAL'], 'EVENT':
# []}

【讨论】:

    猜你喜欢
    • 2019-02-27
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-07-10
    相关资源
    最近更新 更多