دیکت و فایل پایتون
با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
Dict Hash Table
ساختار جدول هش کلید/مقدار کارآمد پایتون "دیکت" نامیده می شود. محتویات یک dict را می توان به صورت مجموعه ای از جفت های کلید:مقدار در داخل پرانتزهای { } نوشت، به عنوان مثال dict = {key1:value1، key2:value2، ... }. "Empty dict" فقط یک جفت پرانتز مجعد خالی {} است.
جستجو کردن یا تنظیم یک مقدار در یک dict از کروشه استفاده می کند، به عنوان مثال dict['foo'] مقدار را در زیر کلید 'foo' جستجو می کند. رشته ها، اعداد و تاپل ها به عنوان کلید کار می کنند و هر نوع می تواند یک مقدار باشد. انواع دیگر ممکن است به عنوان کلید به درستی کار کنند یا ممکن است به درستی کار نکنند (رشته ها و تاپل ها تمیز کار می کنند زیرا تغییرناپذیر هستند). جستجوی مقداری که در دیکته نیست، یک خطای کلیدی ایجاد میکند - از "in" برای بررسی اینکه آیا کلید در دیکته است یا نه از dict.get(key) استفاده کنید که مقدار را برمیگرداند یا اگر کلید وجود نداشته باشد، از None استفاده کنید. یا get(key, not-found) به شما این امکان را می دهد که مشخص کنید چه مقداری را در حالت پیدا نشده برگردانید).
## Can build up a dict by starting with the empty dict {}
## and storing key/value pairs into the dict like this:
## dict[key] = value-for-that-key
dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'
print(dict) ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}
print(dict['a']) ## Simple lookup, returns 'alpha'
dict['a'] = 6 ## Put new key/value into dict
'a' in dict ## True
## print(dict['z']) ## Throws KeyError
if 'z' in dict: print(dict['z']) ## Avoid KeyError
print(dict.get('z')) ## None (instead of KeyError)

یک حلقه for در فرهنگ لغت به طور پیش فرض روی کلیدهای آن تکرار می شود. کلیدها به ترتیب دلخواه ظاهر می شوند. متدهای dict.keys() و dict.values() لیستی از کلیدها یا مقادیر را به طور صریح برمی گرداند. همچنین یک آیتم() وجود دارد که لیستی از تاپل های (key, value) را برمی گرداند که کارآمدترین راه برای بررسی تمام داده های مقدار کلید در فرهنگ لغت است. همه این لیست ها را می توان به تابع sorted() منتقل کرد.
## By default, iterating over a dict iterates over its keys.
## Note that the keys are in a random order.
for key in dict:
print(key)
## prints a g o
## Exactly the same as above
for key in dict.keys():
print(key)
## Get the .keys() list:
print(dict.keys()) ## dict_keys(['a', 'o', 'g'])
## Likewise, there's a .values() list of values
print(dict.values()) ## dict_values(['alpha', 'omega', 'gamma'])
## Common case -- loop over the keys in sorted order,
## accessing each key/value
for key in sorted(dict.keys()):
print(key, dict[key])
## .items() is the dict expressed as (key, value) tuples
print(dict.items()) ## dict_items([('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')])
## This loop syntax accesses the whole dict by looping
## over the .items() tuple list, accessing one (key, value)
## pair on each iteration.
for k, v in dict.items(): print(k, '>', v)
## a > alpha o > omega g > gamma
نکته استراتژی: از نقطه نظر عملکرد، فرهنگ لغت یکی از بهترین ابزارهای شماست و باید از آن در جایی که می توانید به عنوان راهی آسان برای سازماندهی داده ها استفاده کنید. برای مثال، ممکن است یک فایل گزارش را بخوانید که در آن هر خط با یک آدرس IP شروع میشود و دادهها را با استفاده از آدرس IP بهعنوان کلید و فهرست خطوطی که بهعنوان مقدار نشان داده میشود، در یک دیکت ذخیره کنید. پس از خواندن کل فایل، می توانید هر آدرس IP را جستجو کنید و فوراً لیست خطوط آن را مشاهده کنید. فرهنگ لغت داده های پراکنده را می گیرد و آن را به چیزی منسجم تبدیل می کند.
عملگر % به راحتی کار می کند تا مقادیر را از یک dict به یک رشته با نام جایگزین کند:
h = {}
h['word'] = 'garfield'
h['count'] = 42
s = 'I want %(count)d copies of %(word)s' % h # %d for int, %s for string
# 'I want 42 copies of garfield'
# You can also use str.format().
s = 'I want {count:d} copies of {word}'.format(h)
دل
عملگر "del" حذف ها را انجام می دهد. در ساده ترین حالت، می تواند تعریف یک متغیر را حذف کند، گویی آن متغیر تعریف نشده است. همچنین میتوان از Del در عناصر یا برشهای فهرست برای حذف آن قسمت از فهرست و حذف مدخلهای یک فرهنگ لغت استفاده کرد.
var = 6
del var # var no more!
list = ['a', 'b', 'c', 'd']
del list[0] ## Delete first element
del list[-2:] ## Delete last two elements
print(list) ## ['b']
dict = {'a':1, 'b':2, 'c':3}
del dict['b'] ## Delete 'b' entry
print(dict) ## {'a':1, 'c':3}
فایل ها
تابع open() باز می شود و دسته فایلی را برمی گرداند که می توان از آن برای خواندن یا نوشتن یک فایل به روش معمول استفاده کرد. کد f = open('name', 'r') فایل را در متغیر f باز می کند که برای خواندن عملیات آماده است و پس از اتمام از f.close() استفاده کنید. به جای r، برای نوشتن از «w» و برای ضمیمه از «a» استفاده کنید. حلقه استاندارد برای فایلهای متنی کار میکند و از طریق خطوط فایل تکرار میشود (این فقط برای فایلهای متنی کار میکند، نه فایلهای باینری). تکنیک for-loop یک روش ساده و کارآمد برای مشاهده تمام خطوط در یک فایل متنی است:
# Echo the contents of a text file
f = open('foo.txt', 'rt', encoding='utf-8')
for line in f: ## iterates over the lines of the file
print(line, end='') ## end='' so print does not add an end-of-line char
## since 'line' already includes the end-of-line.
f.close()
خواندن یک خط در یک زمان دارای کیفیت خوبی است که لازم نیست همه فایل ها در یک زمان در حافظه قرار گیرند - اگر بخواهید بدون استفاده از 10 گیگابایت حافظه به هر خط در یک فایل 10 گیگابایتی نگاه کنید مفید است. متد f.readlines() کل فایل را در حافظه می خواند و محتویات آن را به عنوان لیستی از خطوط آن برمی گرداند. متد f.read() کل فایل را در یک رشته می خواند، که می تواند روشی مفید برای مقابله با متن به یکباره باشد، مانند عبارات منظم که بعداً خواهیم دید.
برای نوشتن، روش f.write(string) ساده ترین راه برای نوشتن داده در یک فایل خروجی باز است. یا می توانید از "print" با یک فایل باز مانند "print(string, file=f)" استفاده کنید.
فایل های یونیکد
برای خواندن و نوشتن فایلهای رمزگذاریشده یونیکد از حالت «t» استفاده کنید و به صراحت یک رمزگذاری را مشخص کنید:
with open('foo.txt', 'rt', encoding='utf-8') as f:
for line in f:
# here line is a *unicode* string
with open('write_test', encoding='utf-8', mode='wt') as f:
f.write('\u20ACunicode\u20AC\n') # €unicode€
# AKA print('\u20ACunicode\u20AC', file=f) ## which auto-adds end='\n'
توسعه تدریجی تمرین کنید
در ساخت یک برنامه پایتون، همه چیز را در یک مرحله ننویسید. به جای آن فقط یک نقطه عطف اول را مشخص کنید، به عنوان مثال "خوب اولین قدم استخراج لیست کلمات است." کد را بنویسید تا به آن نقطه عطف برسید، و فقط ساختارهای داده خود را در آن نقطه چاپ کنید، و سپس می توانید یک sys.exit(0) انجام دهید تا برنامه در قسمت های انجام نشده اش اجرا نشود. هنگامی که کد نقطه عطف کار می کند، می توانید روی کد برای نقطه عطف بعدی کار کنید. اینکه بتوانید به پرینت متغیرهای خود در یک حالت نگاه کنید، می تواند به شما کمک کند تا در مورد چگونگی تغییر آن متغیرها برای رسیدن به حالت بعدی فکر کنید. پایتون با این الگو بسیار سریع عمل می کند و به شما امکان می دهد کمی تغییر دهید و برنامه را اجرا کنید تا ببینید چگونه کار می کند. از این چرخش سریع برای ساختن برنامه خود در مراحل کوچک استفاده کنید.
تمرین: wordcount.py
با ترکیب تمام مواد اولیه پایتون - رشتهها، فهرستها، دستورات، تاپلها، فایلها - تمرین خلاصه wordcount.py را در تمرینهای پایه امتحان کنید.
جز در مواردی که غیر از این ذکر شده باشد،محتوای این صفحه تحت مجوز Creative Commons Attribution 4.0 License است. نمونه کدها نیز دارای مجوز Apache 2.0 License است. برای اطلاع از جزئیات، به خطمشیهای سایت Google Developers مراجعه کنید. جاوا علامت تجاری ثبتشده Oracle و/یا شرکتهای وابسته به آن است.
تاریخ آخرین بهروزرسانی 2025-07-28 بهوقت ساعت هماهنگ جهانی.
[[["درک آسان","easyToUnderstand","thumb-up"],["مشکلم را برطرف کرد","solvedMyProblem","thumb-up"],["غیره","otherUp","thumb-up"]],[["اطلاعاتی که نیاز دارم وجود ندارد","missingTheInformationINeed","thumb-down"],["بیشازحد پیچیده/ مراحل بسیار زیاد","tooComplicatedTooManySteps","thumb-down"],["قدیمی","outOfDate","thumb-down"],["مشکل ترجمه","translationIssue","thumb-down"],["مشکل کد / نمونهها","samplesCodeIssue","thumb-down"],["غیره","otherDown","thumb-down"]],["تاریخ آخرین بهروزرسانی 2025-07-28 بهوقت ساعت هماهنگ جهانی."],[[["\u003cp\u003ePython uses a "dict" to store key-value pairs, supporting lookups, insertions, and deletions using brackets and built-in methods.\u003c/p\u003e\n"],["\u003cp\u003eIteration over a dict's keys, values, or items is facilitated by methods like \u003ccode\u003ekeys()\u003c/code\u003e, \u003ccode\u003evalues()\u003c/code\u003e, and \u003ccode\u003eitems()\u003c/code\u003e, enabling flexible data processing.\u003c/p\u003e\n"],["\u003cp\u003eFiles in Python are accessed using \u003ccode\u003eopen()\u003c/code\u003e, with modes for reading, writing, and appending, and can be iterated line by line for efficient processing.\u003c/p\u003e\n"],["\u003cp\u003eUnicode files should be opened with the 't' mode and encoding explicitly specified for proper handling of characters.\u003c/p\u003e\n"],["\u003cp\u003eIncremental development is encouraged, where programs are built in stages, focusing on individual milestones and data structure verification.\u003c/p\u003e\n"]]],[],null,["# Python Dict and File\n\nDict Hash Table\n---------------\n\nPython's efficient key/value hash table structure is called a \"dict\". The contents of a dict can be written as a series of key:value pairs within braces { }, e.g. dict = {key1:value1, key2:value2, ... }. The \"empty dict\" is just an empty pair of curly braces {}.\n\nLooking up or setting a value in a dict uses square brackets, e.g. dict\\['foo'\\] looks up the value under the key 'foo'. Strings, numbers, and tuples work as keys, and any type can be a value. Other types may or may not work correctly as keys (strings and tuples work cleanly since they are immutable). Looking up a value which is not in the dict throws a KeyError -- use \"in\" to check if the key is in the dict, or use dict.get(key) which returns the value or None if the key is not present (or get(key, not-found) allows you to specify what value to return in the not-found case). \n\n```python\n ## Can build up a dict by starting with the empty dict {}\n ## and storing key/value pairs into the dict like this:\n ## dict[key] = value-for-that-key\n dict = {}\n dict['a'] = 'alpha'\n dict['g'] = 'gamma'\n dict['o'] = 'omega'\n\n print(dict) ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}\n\n print(dict['a']) ## Simple lookup, returns 'alpha'\n dict['a'] = 6 ## Put new key/value into dict\n 'a' in dict ## True\n ## print(dict['z']) ## Throws KeyError\n if 'z' in dict: print(dict['z']) ## Avoid KeyError\n print(dict.get('z')) ## None (instead of KeyError)\n```\n\n\nA for loop on a dictionary iterates over its keys by default. The keys will appear in an arbitrary order. The methods dict.keys() and dict.values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary. All of these lists can be passed to the sorted() function. \n\n```python\n ## By default, iterating over a dict iterates over its keys.\n ## Note that the keys are in a random order.\n for key in dict:\n print(key)\n ## prints a g o\n\n ## Exactly the same as above\n for key in dict.keys():\n print(key)\n\n ## Get the .keys() list:\n print(dict.keys()) ## dict_keys(['a', 'o', 'g'])\n\n ## Likewise, there's a .values() list of values\n print(dict.values()) ## dict_values(['alpha', 'omega', 'gamma'])\n\n ## Common case -- loop over the keys in sorted order,\n ## accessing each key/value\n for key in sorted(dict.keys()):\n print(key, dict[key])\n\n ## .items() is the dict expressed as (key, value) tuples\n print(dict.items()) ## dict_items([('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')])\n\n ## This loop syntax accesses the whole dict by looping\n ## over the .items() tuple list, accessing one (key, value)\n ## pair on each iteration.\n for k, v in dict.items(): print(k, '\u003e', v)\n ## a \u003e alpha o \u003e omega g \u003e gamma\n```\n\nStrategy note: from a performance point of view, the dictionary is one of your greatest tools, and you should use it where you can as an easy way to organize data. For example, you might read a log file where each line begins with an IP address, and store the data into a dict using the IP address as the key, and the list of lines where it appears as the value. Once you've read in the whole file, you can look up any IP address and instantly see its list of lines. The dictionary takes in scattered data and makes it into something coherent.\n\nDict Formatting\n---------------\n\nThe % operator works conveniently to substitute values from a dict into a string by name: \n\n```python\n h = {}\n h['word'] = 'garfield'\n h['count'] = 42\n s = 'I want %(count)d copies of %(word)s' % h # %d for int, %s for string\n # 'I want 42 copies of garfield'\n\n # You can also use str.format().\n s = 'I want {count:d} copies of {word}'.format(h)\n```\n\nDel\n---\n\nThe \"del\" operator does deletions. In the simplest case, it can remove the definition of a variable, as if that variable had not been defined. Del can also be used on list elements or slices to delete that part of the list and to delete entries from a dictionary. \n\n```python\n var = 6\n del var # var no more!\n\n list = ['a', 'b', 'c', 'd']\n del list[0] ## Delete first element\n del list[-2:] ## Delete last two elements\n print(list) ## ['b']\n\n dict = {'a':1, 'b':2, 'c':3}\n del dict['b'] ## Delete 'b' entry\n print(dict) ## {'a':1, 'c':3}\n```\n\nFiles\n-----\n\nThe open() function opens and returns a file handle that can be used to read or write a file in the usual way. The code f = open('name', 'r') opens the file into the variable f, ready for reading operations, and use f.close() when finished. Instead of 'r', use 'w' for writing, and 'a' for append. The standard for-loop works for text files, iterating through the lines of the file (this works only for text files, not binary files). The for-loop technique is a simple and efficient way to look at all the lines in a text file: \n\n```python\n # Echo the contents of a text file\n f = open('foo.txt', 'rt', encoding='utf-8')\n for line in f: ## iterates over the lines of the file\n print(line, end='') ## end='' so print does not add an end-of-line char\n ## since 'line' already includes the end-of-line.\n f.close()\n```\n\nReading one line at a time has the nice quality that not all the file needs to fit in memory at one time -- handy if you want to look at every line in a 10 gigabyte file without using 10 gigabytes of memory. The f.readlines() method reads the whole file into memory and returns its contents as a list of its lines. The f.read() method reads the whole file into a single string, which can be a handy way to deal with the text all at once, such as with regular expressions we'll see later.\n\nFor writing, f.write(string) method is the easiest way to write data to an open output file. Or you can use \"print\" with an open file like \"print(string, file=f)\".\n\nFiles Unicode\n-------------\n\nTo read and write unicode encoded files use a \\`'t'\\` mode and explicitly specify an encoding: \n\n```python\nwith open('foo.txt', 'rt', encoding='utf-8') as f:\n for line in f:\n # here line is a *unicode* string\n\nwith open('write_test', encoding='utf-8', mode='wt') as f:\n f.write('\\u20ACunicode\\u20AC\\n') # €unicode€\n # AKA print('\\u20ACunicode\\u20AC', file=f) ## which auto-adds end='\\n'\n```\n\nExercise Incremental Development\n--------------------------------\n\nBuilding a Python program, don't write the whole thing in one step. Instead identify just a first milestone, e.g. \"well the first step is to extract the list of words.\" Write the code to get to that milestone, and just print your data structures at that point, and then you can do a sys.exit(0) so the program does not run ahead into its not-done parts. Once the milestone code is working, you can work on code for the next milestone. Being able to look at the printout of your variables at one state can help you think about how you need to transform those variables to get to the next state. Python is very quick with this pattern, allowing you to make a little change and run the program to see how it works. Take advantage of that quick turnaround to build your program in little steps.\n\nExercise: wordcount.py\n----------------------\n\nCombining all the basic Python material -- strings, lists, dicts, tuples, files -- try the summary **wordcount.py** exercise in the [Basic Exercises](/edu/python/exercises/basic)."]]