功能:读取一个文件,然后添加多个项目到字典 [英] Function: Read a file then add multiple items to dictionary

查看:81
本文介绍了功能:读取一个文件,然后添加多个项目到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试创建一个函数来读取一个文件,并将其他多个项目添加到有组织的字典中,然后返回它而不改变原始字典。不确定我是否正确使用多个项目和值。

Trying create a function to read a file and add additional multiple items to it into an organized dictionary then return it without changing the original dictionary. Not sure if I'm doing it correctly with the multiple items and values.

返回:

{'Leonardo da Vinci': [("Portrait of Isabella d'Este", 1499, 63.0, 46.0, 'chalk', 'France'), ('The Last Supper', 1495, 460.0, 880.0, 'tempera', 'Italy')], 'Pablo Picasso': [('Guernica', 1937, 349.0, 776.0, 'oil paint', 'Spain')]}

示例文件:

file1='''"Artist","Title","Year","Total Height","Total Width","Media","Country"
"Pablo Picasso","Guernica","1937","349.0","776.0","oil paint","Spain"
"Leonardo da Vinci","The Last Supper","1495","460.0","880.0","tempera","Italy"'''

代码我到目前为止:

def add_work (db,artist,title,year,height,width,media,country):
db = {}
    with open(filename) as f:
    for line in f:
        (title, year, height, width, media, country) = line.split()
        db[int(artist)] = (title, year, height, width, media, country)
        for i in d.keys():
            if i == artist #If artist in dictionary, then add it to item.
                db[i].extend
            elif i == title #If it has the same title as in the database, its a duplicate so return none.
                return None
add_work(d1,"Leonardo   da  Vinci","Portrait of Isabella d'Este", 1499, 63.0,46.0, "chalk", "France")

限制:


  1. Asciibetical订单:按照ASCII
    整理顺序排序,而不是按字母顺序排列。

  1. Asciibetical order: Is sorted in ASCII collated order rather than alphabetical order.

否import / collections / modules。只是基本内置的函数,循环和dict方法。

No imports/collections/modules. Just basic built in functions, loops, and dict methods.


推荐答案

我们在评论中讨论过,您的主要问题是找出在哪里将新画放在艺术家绘画的列表中。

As we discussed in the comments, your main problem is figuring out where to place the new painting in the list of an artist's paintings based on it's title.

出现对我来说,这是一个家庭作业的问题,因为在现实世界中没有理由这些限制。因为我不会给你完整的解决方案,而是指向正确的方向(至少我会尝试)。

您的算法应该如下所示:

Your algorithm should look something like this:


  1. 获取一个名称为艺术家的字典作为关键字,并列出他的画作为价值观。每幅画由标题 height width media country

给定一组新的艺术家标题 height width media 国家/地区您检索该艺术家工作的列表。

Given a new set of artist, title, year, height, width, media and country you retrieve the list of that artists work.

问题是找出在哪里添加新的绘画(如果它还不存在)。

Now your problem is to find out where to add the new painting (if it doesn't already exist).

你循环浏览上述列表中的所有绘画。对于每个条目,您检查新工作的标题是否应在当前标题之前使用 compare_to - 以下功能。如果是( -1 )插入。如果结果是 0 它已经在列表中,并返回字典。如果结果是 1 ,则转到列表的下一个项目。如果没有更多的项目你追加到最后。

You loop through all paintings in the aforementioned list. For each entry you check if the title of the new work should be inserted before the current title using the compare_to-function below. If yes (-1) you insert it. If the result is 0 it is already in the list and you return the dictionary. If the result is 1 you move on to the next item of the list. If there are no more items you append it to the end.

这是 compare_to 函数:

def compare_to(string_1, string_2):
    """
    This functions returns -1 if string_1 should be inserted before string_2,
    0 if the strings are the same (in which case it doesn't matter - or this
    shouldn't happen) and 1 if string_1 is supposed to be inserted after
    string_2.
    """
    abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    if string_1 == string_2:
        return 0

    for i in range(min(len(string_1), len(string_2))):
        if abc.index(string_1[i]) < abc.index(string_2[i]):
            return -1

    # The strings are not the same, the shorter one should come first
    if len(string_2) > len(string_1):
        return -1

    return 1

我不知道在比较中如何处理数字,请随意将它们添加到 abc 变量中。

I don't know how you'd like to handle numbers in the comparison, feel free to add them to the abc variable.

这篇关于功能:读取一个文件,然后添加多个项目到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆