|
在当前代码中,我正在执行测试以处理数量可变的字典:我正在寻找一种方法来获取所有密钥及其值。在当前示例中,特别是在DictionnaryTest2功能中,我未能将 Tuple 更改为原始列表,以便获取密钥名称(并且错误即将出现):我想知道我是否使用了正确的方法(这是第一次),因此如何继续?- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- import numpy as np
-
- # A dictionnary is created
- n = 10
- m = 1
- X = np.random.random( (n,m) )
- Y = np.random.random( (n,m) )
- Z = np.random.random( (n,m) )
- MyDictionnary = {'Abcissa': X, 'Ordinate': Y, 'Altitude': Z}
- MyDictionnary2 = {'Abcissa2': X, 'Ordinate2': Y, 'Altitude2': Z, 'Theta': (X+Y)}
- del X, Y, Z
-
- # Dictionnary keys are listed / the dictionnary is explicitly expressed
- KeyList0 = list(MyDictionnary.keys())
- print("Key list (explicitly) : {}".format(KeyList0))
-
-
- # Dictionnary keys are listed / the dictionnary name is a variable
- MyVar = 'MyDictionnary'
- KeyList1 = list(locals()[MyVar].keys())
- print("Key list (name=variable) : {}".format(KeyList1))
-
-
- # Now inside a function with the dictionnary in argument
- def DictionnaryTest1(MyDict):
- NewVar = 'MyDict'
- KeyListFunction = list(locals()[NewVar].keys())
- print("Key list in a function : {}".format(KeyListFunction))
- return
-
- KeyList1 = DictionnaryTest1(MyDictionnary)
-
-
-
- # A list a dictionnary names is now created
- DictionnaryNamesTables = ['MyDictionnary', 'MyDictionnary2']
-
- # just for printing the dictionnaries list
- for i in range(len(DictionnaryNamesTables)):
- print(DictionnaryNamesTables[i])
-
-
- def DictionnaryTest2(*args):
-
- # tests
- print("Type args = {}".format(type(args)))
- print("length args = {}".format(len(args)))
- print("args = {}".format(args))
- args = list(args)
- print("length args (after list())= {}".format(len(args)))
- NumberOfDictionnaries = len(args)
-
- for i in range(len(args)):
- NewVar = args[i] #
- print("NewVar = {}".format(NewVar))
- KeyListFunction2 = list(locals()[NewVar].keys())
- print("KeyListFunction2 = {}".format(KeyListFunction2))
-
- return
-
- KeyList2 = DictionnaryTest2(DictionnaryNamesTables)
复制代码
|
|