【问题标题】:How can I split values of a dictionary by comma?如何用逗号分割字典的值?
【发布时间】:2020-09-28 16:01:33
【问题描述】:
games = {
"1":"GTA V,FarCry 5",
"2":"Watchdogs II,South Park: The Stick of Truth",
"3":"For Honor,The Forest,South Park: The Fractured but whole"}

for games_value in games.values():
    games_value.split(",")

但这无济于事......

我想要什么:

games = {
"1":"GTA V","FarCry 5"
"2":"Watchdogs II","South Park: The Stick of Truth"
"3":"For Honor","The Forest","South Park: The Fractured but whole"}

提前致谢!

【问题讨论】:

  • 这能回答你的问题吗? How to create a dictionary whose values are sets?
  • 但是通过这样做我创建了一个新字典...我没有使用原来的字典(我没有通过字符串操作编辑字典...做这个方法我创建了一个全新的字典或者我误解?)

标签: python dictionary split key-value-store


【解决方案1】:

您已接近解决方案,请查看此代码。

games = {
"1":"GTA V,FarCry 5",
"2":"Watchdogs II,South Park: The Stick of Truth",
"3":"For Honor,The Forest,South Park: The Fractured but whole"
}

for games_key in games:
    games[games_key] = games[games_key].split(",")

print(games)

#OUTPUT: {'1': ['GTA V', 'FarCry 5'], '2': ['Watchdogs II', 'South Park: The Stick of Truth'], '3': ['For Honor', 'The Forest', 'South Park: The Fractured but whole']}

逻辑:

  • 遍历字典键
  • 在字典键处写入拆分的值

看看dictionary reference

【讨论】:

  • 哦,是的!你完全正确!泰!但是,我将字典转换为元组没有?
  • 由于时间限制无法xD
  • @zoramind 此代码保持字典类型,分配给键的值是列表类型
猜你喜欢
  • 2022-03-18
  • 2019-03-31
  • 1970-01-01
  • 2010-12-11
  • 2020-08-30
  • 1970-01-01
  • 2020-10-25
  • 2014-07-14
相关资源
最近更新 更多