相关疑难解决方法(0)

如何在Python中将2个字典变成1个?

我有两本词典:

fruit1 = {'apple': 3, 'banana': 1, 'cherry': 1}
fruit2 = {'apple': 42, 'peach': 1}
Run Code Online (Sandbox Code Playgroud)

我想要的最终结果是:

inv3 = {'apple': 45, 'banana': 1, 'cherry': 1, 'peach': 1}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试过这个示例代码,因为这个输出看起来几乎与我想要的类似,只是它没有按照我想要的方式打印,而是接近:

d1 = {'apple': 3, 'orange': 1,} 
d2 = {'apple': 42, 'orange': 1}

ds = [d1, d2]
d = {}

for k in d1.keys():
    d[k] = tuple(d[k] for d in ds)
print(ds)
Run Code Online (Sandbox Code Playgroud)

输出将是这样的:

[{'apple': 3, 'orange': 1}, {'apple': 42, 'orange': 1}]
Run Code Online (Sandbox Code Playgroud)

当我尝试使用示例代码输入我的两个词典时:

fruit1 = {'apple': 3, 'banana': 1, 'cherry': 1}
fruit2 = {'apple': 42, …
Run Code Online (Sandbox Code Playgroud)

python dictionary list key-value

0
推荐指数
1
解决办法
109
查看次数

如何访问python中的dicts列表中的属性?

假设我有一个词典:

firstdict = {"somelist":[]}
Run Code Online (Sandbox Code Playgroud)

我有另一个词:

  seconddict = {"attribute1": "value1", "attribute2": "value2"}
Run Code Online (Sandbox Code Playgroud)

附上字典后

firstdict["somelist"].append(seconddict)
Run Code Online (Sandbox Code Playgroud)

我想打印"attribute1"值.虽然以下声明不起作用:

print firstdict["somelist"][0].attribute1
Run Code Online (Sandbox Code Playgroud)

如何打印/访问attribute1的值?

python

-1
推荐指数
1
解决办法
78
查看次数

我如何获得这种字典数组

我有一个函数,它将 id、name、age、country 作为输入,并将其放入字典中的字典中,如下所示:{0:{Name: "Name1", Age: 21, Country: "Country1}}。我打算把它放在一个数组中。 我希望我的字典数组看起来像这样

[
  {
    0: {
      'Name': 'Name1',
      'Age': 21,
      'Country': 'Country1'
    },
    1: {
      'Name': 'Name2',
      'Age': 22,
      'Country': 'Country2'
    },
    3: {
      'Name': 'Name3',
      'Age': 23,
      'Country': 'Country3'
    }
  }
]
Run Code Online (Sandbox Code Playgroud)

但是,我当前的数组如下所示:

[
  {
    0: {
      'Name': 'Name1',
      'Age': 21,
      'Country': 'Country1'
    }
  },
  {
    1: {
      'Name': 'Name2',
      'Age': 22,
      'Country': 'Country2'
    }
  },
  {
    3: {
      'Name': 'Name3',
      'Age': 23,
      'Country': 'Country3'
    }
  }
]
Run Code Online (Sandbox Code Playgroud)

两者之间在括号 …

python

-1
推荐指数
1
解决办法
80
查看次数

使用for循环将元素添加到列表中的现有字典中

我有以下词典列表:

d = [{'Sport': 'MLB', 'Position': 'SP', 'Age': '25'},
     {'Sport': 'NBA', 'Position': 'PG', 'Age': '28'}]
Run Code Online (Sandbox Code Playgroud)

我有另一个列表,我想通过使用for循环追加到上面:

c = [{'2015 Salary' : '25'}, {'2015 Salary': '35'},
    {'2016 Salary' : '30'}, {'2016 Salary' : '40'}]
Run Code Online (Sandbox Code Playgroud)

我希望最终输出

e = [{'Sport': 'MLB', 'Position': 'SP', 'Age': '25', '2015 Salary': '25',  
     '2016 Salary': '30'},
     {'Sport': 'NBA', 'Position': 'PG', 'Age': '28', '2015 Salary': '35',  
     '2016 Salary': '40'}}]
Run Code Online (Sandbox Code Playgroud)

这些位置总是和我使用for循环的原因相同.

python for-loop

-3
推荐指数
1
解决办法
116
查看次数

标签 统计

python ×4

dictionary ×1

for-loop ×1

key-value ×1

list ×1