迭代数组并创建新的字典

时间:2018-01-04 09:50:29

标签: python

我有一个使用python pyVmomi模块从vcenter获得的数组

数组名称为clustr_group_info,如下所示

>>> type(clustr_group_info)
<class 'pyVmomi.VmomiSupport.vim.cluster.GroupInfo[]'>

数组的内容如下所示:

print(clustr_group_info)
(vim.cluster.GroupInfo) [
(vim.cluster.VmGroup) {
  dynamicType = <unset>,
  dynamicProperty = (vmodl.DynamicProperty) [],
  name = 'group1',
  userCreated = <unset>,
  uniqueID = <unset>,
  vm = (vim.VirtualMachine) []
},
(vim.cluster.HostGroup) {
  dynamicType = <unset>,
  dynamicProperty = (vmodl.DynamicProperty) [],
  name = 'group2',
  userCreated = <unset>,
  uniqueID = <unset>,
  host = (vim.HostSystem) [
     'vim.HostSystem:host-631607',
     'vim.HostSystem:host-631791'
  ]
},

我需要使用&#34; name&#34;为每次迭代创建一个新的字典。作为关键和 &#34;主机&#34;作为一种价值 我无法以常规方式迭代数组

>>> for i in clustr_group_info[0]:
...     print(i)

追踪(最近一次通话):   文件&#34;&#34;,第1行,in TypeError:&#39; vim.cluster.VmGroup&#39;对象不可迭代

1 个答案:

答案 0 :(得分:0)

遍历整个数组,而不是其中的第一项[0]。像这样:

for i in clustr_group_info:
    print(i.['name']) # If it's a dictionary
    print(i.name) # If it's an object of a class