In the current code, I’m performing tests to works with a variable number of dictionaries; I’m looking for a way to get all keys and their values.
In the current example, especially in DictionnaryTest2 function, I fail in changing the tuple into the original list, in order to get key names (and an error is coming): I’m wondering if I’m using the right way (this is the first time) and so how to proceed?
Thanks for any advice
In the current example, especially in DictionnaryTest2 function, I fail in changing the tuple into the original list, in order to get key names (and an error is coming): I’m wondering if I’m using the right way (this is the first time) and so how to proceed?
Thanks for any advice
#!/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)Output:Type args = <class 'tuple'>
length args = 1
args = (['MyDictionnary', 'MyDictionnary2'],)
length args (after list())= 1
NewVar = ['MyDictionnary', 'MyDictionnary2']and the (logical) errorError:TypeError: unhashable type: 'list'
