How to print a dictionary's key?

前端 未结 20 806
眼角桃花
眼角桃花 2020-11-27 09:22

I would like to print a specific Python dictionary key:

mydic = {}
mydic[\'key_name\'] = \'value_name\'

Now I can check if mydic.has_

20条回答
  •  無奈伤痛
    2020-11-27 09:35

    # highlighting how to use a named variable within a string:
    mapping = {'a': 1, 'b': 2}
    
    # simple method:
    print(f'a: {mapping["a"]}')
    print(f'b: {mapping["b"]}')
    
    # programmatic method:
    for key, value in mapping.items():
        print(f'{key}: {value}')
    
    # yields:
    # a 1
    # b 2
    
    # using list comprehension
    print('\n'.join(f'{key}: {value}' for key, value in dict.items()))
    
    
    # yields:
    # a: 1
    # b: 2
    

    Edit: Updated for python 3's f-strings...

提交回复
热议问题