Python:单独打印字典键和值

时间:2016-01-24 05:13:21

标签: python-3.x

我想知道:如何从函数中的字典中单独打印键或值?

示例.txt文件

test_file = open("test.txt", "r")
customer = {}
def dictionary():
    for line in test_file:
        entries = line.split(";")
        key = entries[0]
        values = entries[1]
        customer[key] = values

def test():
    print(customer)
    print(customer[key])

def main():
    dictionary()
    test()

main()

代码

<?php
    $path=$post->file_path;
    $path1=base64_encode($path);
?>
<p>Download uploaded file</p>
<a href="<?php echo base_url('index.php/fileupload/download/'.$path1);?>">Download</a>

1 个答案:

答案 0 :(得分:0)

如@jamesRH所述,您可以使用customer.keys()customer.values()

test_file = open("test.txt", "r")
customer = {}
def dictionary():
    for line in test_file:
        entries = line.split(";")
        key = entries[0]
        values = entries[1]
        customer[key] = values

def test():
    # Print all the keys in customer
    print(customer.keys())

    # Print all the values in customer
    print(customer.values())

def main():
    dictionary()
    test()

main()

这给出了输出:

['00000000', '22222222', '33333333', '11111111']
['Pikachu Muchacho', 'Marshaw williams', 'larry Mikal Carter', 'SoSo good']

您的原始代码会导致错误,因为key不在test()的范围内。