Home > Software engineering >  how to show .npy files' name in a .npz file, using .keys( )
how to show .npy files' name in a .npz file, using .keys( )

Time:04-27

I used .keys() to see the .npy files in a .npz file:

a1 = np.arange(5)
a2 = np.arange(6)
np.savez('zip1.npz', file1 = a1, file2 = a2)
data2 = np.load('zip1.npz')
data2.keys()

Output:

KeysView(<numpy.lib.npyio.NpzFile object at 0x0000016D49CA9F10>)

I saw somewhere else that .keys() outputs the .npy files' name:

np.savez('x.npz', a = array1, b = array2)
data = np.load('x.npz')
data.keys()

With this output:

['b','a']

Why is it? Thank you!

CodePudding user response:

In [223]: d = np.load('data.npz')
In [224]: d
Out[224]: <numpy.lib.npyio.NpzFile at 0x7f93fae26040>

keys() on a dict or dict like object produces 'view' that can be used for iteration, or expanded with list. This behavior is widespread in Py3.

In [225]: d.keys()
Out[225]: KeysView(<numpy.lib.npyio.NpzFile object at 0x7f93fae26040>)
In [226]: list(d.keys())
Out[226]: ['fone', 'nval']

iterating:

In [228]: for k in d.keys():
     ...:     print(k, d[k])
fone ['t1' 't2' 't3']
nval [1 2 3]

another common case:

In [229]: range(3)
Out[229]: range(0, 3)
In [230]: list(range(3))
Out[230]: [0, 1, 2]
  • Related