items and iteritems difference manipulate files and Python dict of

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_37189082/article/details/100305265

How 1.Python is manipulating files?

open a file

Write or read data

Close the file

# 写文件,test.txt要操作文本名
f = open('test.txt', 'wt')   # 以wt(write text)写入文本方式去打开
f.write("hello world")       # 写入字符串
f.close                      # 关闭

# 使用with,追加内容,不用关心文件关闭问题
# with方法会在操作完成之后自动关闭
with open('test.txt', 'at') as f:  # 以at(add text)追加文本方式操作
    f.write("\nhello xiaokang")
    
# 读取文件
with open('test.txt', 'rt') as f: # 以rt(read text)读取文本方式操作
    print(f.read())

items and iteritems 2. dict the difference?

Python2 the items list method (list) returns embodiment, in no particular order return; iteritems similar method, but returns an iterator (Iterator) object. items returned iteration object, iteritems returns an iterator.

Python3 no iteritems method, items may be returned iterator object.

test1 = {'key1':2, 'key2':3, 'key3':4}

# python2
kv1 = test1.items()       # 返回一个包含字典中(键,值)对元组的列表
print(kv1)     # 输出结果: [('key3', 4), ('key2', 3), ('key1', 2)]
kv2 = test1.iteritems()   # 返回对字典中所有(键,值)对的迭代器
print(type(kv2))    # 输出结果: <type 'dictionary-itemiterator'>
print(next(kv2))    # 输出结果: ('key3', 4)
print(next(kv2))    # 输出结果: ('key2', 3)
print(next(kv2))   # 输出结果: ('key1', 2)

# python3
kv3 = test1.items()    # 以列表返回可遍历的(键, 值) 元组数组
print(kv3) # 输出结果: dict_items([('key1', 2), ('key2', 3), ('key3', 4)])
from collections import Iterable, Iterator
print(isinstance(kv3, Iterable))  # 输出结果: True
print(isinstance(kv3, Iterator))  # 输出结果: False
for key,value in kv3:
    print("key:" + key, end =' ')
    print("value:" + str(value))
# 输出结果:
    key:key1 value:2
    key:key2 value:3
    key:key3 value:4

Guess you like

Origin blog.csdn.net/qq_37189082/article/details/100305265