Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Peter Otten <__peter__@web.de> Newsgroups: comp.lang.python Subject: Re: how to create a dictionary from csv file? Date: Tue, 26 Apr 2016 16:40:37 +0200 Organization: None Lines: 62 Message-ID: References: <246c571e-1793-4aa6-9405-19d7a1355598@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Trace: news.uni-berlin.de gcw1iOZdnRX4IdkeLJxbqgsnqIefJTjTHRwVkijprojA== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.001 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'subject:file': 0.07; 'csv': 0.09; 'lookup': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'subject:create': 0.09; 'python': 0.10; 'python.': 0.11; 'suggest': 0.15; 'file,': 0.15; '3.0,': 0.16; 'list)': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:io': 0.16; 'received:plane.gmane.org': 0.16; 'received:psf.io': 0.16; 'received:t-ipconnect.de': 0.16; 'wrote:': 0.16; '>>>': 0.20; 'keys': 0.22; '(or': 0.23; 'import': 0.24; 'header:User-Agent:1': 0.26; 'header:X-Complaints-To:1': 0.26; 'dictionary': 0.29; 'anyone': 0.32; 'file': 0.34; 'skip:3 10': 0.35; 'but': 0.36; 'to:addr:python-list': 0.36; 'subject:?': 0.36; 'subject:: ': 0.37; 'received:org': 0.37; 'mailing': 0.38; 'subject:from': 0.39; 'to:addr:python.org': 0.40; 'received:de': 0.40; "you'll": 0.61; 'show': 0.62; 'success': 0.62; 'more': 0.63; 'tutor': 0.66; 'here': 0.66; 'yourself,': 0.72; 'gaps': 0.93 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: p57bd8a17.dip0.t-ipconnect.de User-Agent: KNode/4.13.3 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.22 Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-Mailman-Original-Message-ID: X-Mailman-Original-References: <246c571e-1793-4aa6-9405-19d7a1355598@googlegroups.com> Xref: csiph.com comp.lang.python:107654 +dime+ wrote: > I am learning python. > > if I have a csv file, like this > banana,4.0 > apple,3.5 > orange,3.0 > > Can anyone show me how to read the csv file line by line and then create a > dictionary to contain these keys and values? Below is a spoiler, but learning Python is more fun and you'll see success sooner when you try to come up with a solution yourself, present it here (or on the tutor mailing list) and let us fill the gaps or suggest improvements. >>> import csv >>> with open("fruit.csv") as f: ... lookup = {k: float(v) for k, v in csv.reader(f)} ... >>> lookup {'orange': 3.0, 'apple': 3.5, 'banana': 4.0} >>> 2*lookup["banana"] + 3*lookup["orange"] 17.0