【问题标题】:key word args to dictionary关键字 args 到字典
【发布时间】:2021-05-03 12:40:11
【问题描述】:

有没有办法将所有的键和值或项放到一个字典中?

 def file_lines( **kwargs):
        for key, username in kwargs.items():
            convert_to_string = str(len(username))
            #a = key +":"+ convert_to_string
            dict = {}
            v = dict[key]= convert_to_string
            print(dict)
    file_lines(
          F1 = "C://downloads/Anime",
          F2 = "C://downloads/Manga",
          F3 = "C://downloads/Music",
          F4 = "C://downloads/Images")

上面的代码运行后得到的答案:

{'F1': '19'} {'F2': '19'} {'F3': '19'} {'F4': '20'}

【问题讨论】:

  • **kwargs 是一本字典。你期望得到什么?
  • 是的,但我希望答案是这样的:{F1: 19, F2:19, F3:20, F4:20} 有没有可能的方法来做到这一点
  • 输出不符合预期的原因是您在循环中创建了一个新的dict。将dict = {} 移到循环之外,应该没问题。

标签: python python-3.x jupyter-notebook


【解决方案1】:

试试:

def file_lines( **kwargs):
    temp= {}
    for key, username in kwargs.items():
        convert_to_string = str(len(username))
        temp[key]= convert_to_string
    return temp

输出:

file_lines(
      F1 = "C://downloads/Anime",
      F2 = "C://downloads/Manga",
      F3 = "C://downloads/Music",
      F4 = "C://downloads/Images")

{'F1': '19', 'F2': '19', 'F3': '19', 'F4': '20'}

【讨论】:

  • 不要使用 dict 作为变量名 - 它会隐藏内置的 dict 类型。
  • 我刚刚编辑了@johnmelvin esguerra 代码。好吧,我已经编辑了我的答案
  • 非常感谢,我一直将 dict = { } 放在 for 循环中,是的,我会记住这一点
【解决方案2】:

试试这个:

def file_lines( **kwargs):
        dict = {}
        for key, username in kwargs.items():
            dict[key]= str(len(username))
        print(dict)

file_lines(
          F1 = "C://downloads/Anime",
          F2 = "C://downloads/Manga",
          F3 = "C://downloads/Music",
          F4 = "C://downloads/Images")

你的错误是你在循环内初始化dict...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2016-09-10
    • 1970-01-01
    • 2019-02-23
    • 2017-11-26
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多