【问题标题】:How to use a Python dictionary? [closed]如何使用 Python 字典? [关闭]
【发布时间】:2017-12-17 17:50:51
【问题描述】:

我发现在 python 中遍历字典很困难。

我已经通过 CodeAcademy 完成了学习和单人学习,但仍然很难通过字典。

除了 Python 的官方文档之外,还有什么好的资源可以让我了解更多信息并以清晰的语言提供,让我可以更熟悉 Python。

【问题讨论】:

    标签: python


    【解决方案1】:

    许多不同的文档和教程资源可用于 Python 在线,根据您的需要,几乎每一个都对您有所帮助。但最可靠的文档是 Python 网站的官方文档。

    另外,请观看相同的 youtube 视频,许多字典和其他 Python 结构的实际实现视频都以易于理解的方式提供。

    这里是字典实现的示例程序:

    my_dict = {'name':'Deadpool', 'designation': 'developer'}
    print(my_dict)
    Output: { 'designation': developer, 'name': Deadpool}
    
    # update value
    my_dict['designation'] = 'sr developer'
    
    #Output: {'designation': sr developer, 'name': Deadpool}
    print(my_dict)
    
    # add an item to existing dictionary
    my_dict['address'] = 'New York'  
    print(my_dict)
    # Output: {'address': New York, 'designation': sr developer, 'name': Deadpool}
    

    【讨论】:

    • “输出:{ 'designation': developer, 'name': Deadpool}”当然应该注释掉...
    【解决方案2】:

    如果您使用的是 Python 2

    for key, value in d.iteritems():
    

    对于 Python 3

    for key, value in d.items():
    

    像往常一样,文档是最好的信息来源 Python 2 Python 3

    【讨论】:

      【解决方案3】:

      具有讽刺意味的是,尽管您正在寻找替代资源,但请相信我,没有任何文档或参考书可以击败 Python 官方文档,因为它始终是最新且最接近 Python 语言的。

      浏览main python website上的不同版本。

      Dictionary : https://docs.python.org/3/tutorial/datastructures.html#dictionaries

      这里还有一个网站,其中有很多 Python resources(即使是针对特定职业),但正如我之前所说的,没有什么能比 Python 官方文档更好。

      另一个链接:python wiki

      理解字典,以下来自官方python文档网站...

      ## dictionary initialization
      >>> tel = {'jack': 4098, 'sape': 4139}
      
      ## set value for a key (either existing or new)
      >>> tel['guido'] = 4127
      
      ## print dictionary
      >>> tel
      {'sape': 4139, 'guido': 4127, 'jack': 4098}
      
      ## get value for an existing key
      >>> tel['jack']
      4098
      
      ## delete a key from dictionary
      >>> del tel['sape']
      
      ## add a new key with value
      >>> tel['irv'] = 4127
      
      ## print dictionary
      >>> tel
      {'guido': 4127, 'irv': 4127, 'jack': 4098}
      
      ## get all keys in dictionary
      >>> list(tel.keys())
      ['irv', 'guido', 'jack']
      
      ## get all keys in dictionary (sorted)
      >>> sorted(tel.keys())
      ['guido', 'irv', 'jack']
      
      ## check if a key exists in dictionary
      >>> 'guido' in tel
      True
      
      ## check if a key exists in dictionary
      >>> 'jack' not in tel
      False
      
      ## Finally iterating thru dictionary
      for key, value in tel.items():
          print(key, value)
      

      【讨论】:

        【解决方案4】:
        # In Python 3.x
        
        hash={'a': 1, 'b': 2}
        
        for k in hash:
            print (str(k) + "," + str(hash[k]))
        
        # OR
        for key, value in hash.items():
            print (str(key) + ',' + str(value))
        
        # OR
        for key, value in {'a': 1, 'b': 2}.items():
            print (str(key) + ',' + str(value))
        
        # OR
        for tup in hash.items():
            print (str(tup[0]) + ',' + str(tup[1]))
        

        【讨论】:

        • NB:hash 是内置的。避免使用。会打破 ish。
        【解决方案5】:
        Dict = { 1 : 'Suri' , 'Fname' : 'Sam' , 'Lname' : 'Saiksas' , 'village' : 'AKP' }
        print ( Dict )
        

        内置dict方法创建字典:

        Dict2 = dict ( { 1 : 'john' , 2 : 'Pam' , 3 : 'google' } )
        print ( Dict2 )
        

        使用对创建字典:

        Dict3 = dict ( [ ('1' , 'Techies') , (2 , 'For') ] )
        print ( Dict3 )
        

        从其他数据结构中创建字典 - 元组列表 如果列表中有任何重复的元组,则只打印一个值:

        list1 = [ (2 , 3) , (4 , 5) , (4 , 5) ]
        print ( dict ( list1 ) )
        

        为字典赋值:

        exDict = { }
        exDict [ 'Key_1' ] = 'Welcome'
        exDict [ 'Key_2' ] = 'Good'
        exDict [ 'Key_3' ] = 'Morning'
        exDict [ 'Key_4' ] = 'Deo'
        print ( exDict )
        

        将一个值集分配给一个键 - 将多个值分配给一个键:

        exDict[ 'Key_1' ] = 'Welcome' , 'Mr' , 'Graham'
        print ( exDict )
        

        使用 Get 方法从字典中获取值:

        print ( '\n' , exDict.get ( 'Key_4' ) )
        print ( '\n' )
        
        print ( "|{0}|,|{1}|,{2}|".format ( exDict [ 'Key_1' ] , exDict [ 'Key_2' ] , exDict [ 'Key_3' ] ) )
        

        从字典中删除项目:

        print ( exDict.values ( ) )
        exDict.pop ( 'Key_1' )
        print ( "After popping an element " , exDict )
        print ( '\n' , 'This is the copy of dict' , exDict.copy ( ) )
        print ( '\n' )
        print ( '\n' )
        

        删除整个字典:

        print ( exDict.values ( ) )
        print ( '\n' )
        print ( exDict.items ( ) )
        exDict.clear ( )
        print ( '\n' )
        print ( exDict )
        

        【讨论】:

          【解决方案6】:

          您需要检查一下

          首当其冲的 Python

          http://www.headfirstlabs.com/books/hfpython/

          这将改变你的生活,让学习 PYTHON 变得有趣。您将掌握 Python 的每个概念,而不是一味地抄袭它。这本书有一个非常直观的方式让你理解python。

          这本书对字典和其他核心概念有详细的解释。

          【讨论】:

          • 建议链接到字典/迭代小节。
          • 由于这本书不是免费提供的。我将保留书中可以找到字典参考的部分。 第 6 章 -> 使用字典关联数据(第 178 页)
          【解决方案7】:

          字典是 Hash 表的 Python 等价物。它将值存储为键值对。值可以是任何 python 对象,而键需要是不可变的。

          以下是在python中遍历字典的一些方法

          # Iterating over the keys.
          for k in dict:
          for k in dict.keys():
          
          #Iterating over the values.
          for v in dict.values():
          
          #Iterating over both the key and values.
          for k,v in dict.items():
          

          【讨论】:

            【解决方案8】:

            我认为学习具有不同值的相同键的 Python 字典会很有用。

            dict1 = {"idno" : 101, "name" : "A"}
            
            dict2 = {"idno" : 102, "name" : "B","contact_no" : 99999999999}
            # if we have two dictionaries with the same keys and different values, in that case if we try to merge two dicts
            # then values will be updated with the same key. 
            # So that we cant access both dictinary's values.
            # if you could see below code, using dict comprehension we can merge two dictionaries in single line 
            merged_dict = {x : [dict1,dict2][x] for x in range(len([dict1,dict2]))}
            print(merged_dict)
            
            # if you want to update value then you can go with below code
            merged_dict = {**dict1,**dict2}
            print(merged_dict)
            

            【讨论】:

              猜你喜欢
              • 2015-01-23
              • 2016-06-04
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2010-11-03
              • 1970-01-01
              相关资源
              最近更新 更多