从先前字典中的值创建新字典

时间:2017-11-12 04:48:24

标签: python python-3.x

我必须编写以下函数(我尝试编写它的方式)。显然我的代码有问题,或者我不会在这里发帖:)根据它在我尝试使用它时给出的消息我知道什么是错的,我明白它是什么 - 写image_dict [0] [1]不起作用,因为键不是0.我需要知道如何使用它的确切键但当然键可以是任何东西所以我想知道我是否可以轻松更改我的代码,使其适用于任何密钥。例如,我可以放置一些代替0的东西,以便它适用于所有键,而不是必须指定确切的键吗?谢谢!

def create_date_dict(image_dict):
'''(dict) -> dict

Given an image dictionary, return a new dictionary
where the key is a date and the value  is a list
of filenames of images taken on that date.

>>> d = {'image1.jpg': ['UTSC', '2017-11-03','Happy Friday']}
>>> date_d = create_date_dict(d)
>>> date_d == {'2017-11-03': ['image1.jpg']}
True
'''
result = {}
for (k, v) in image_dict.items():
    result[image_dict[0][1]] = [image_dict[0]]
return result

4 个答案:

答案 0 :(得分:3)

我从@coldspeed学到的另一个非常酷的方法是摆脱导入:

# Data from @Miraj50
d = {'image1.jpg': ['UTSC', '2017-11-03','Happy Friday'], 'image2.jpg': ['UTSC', '2017-09-04','Happy Monday'], 'image3.jpg': ['UTSC', '2017-11-03','Happy Monday']}

k = {}

for x, y in d.items():
    k.setdefault(y[1], []).append(x)

{'2017-09-04': ['image2.jpg'], '2017-11-03': ['image1.jpg', 'image3.jpg']}

答案 1 :(得分:2)

我用defaultdict来获得你想要的东西。见这个例子。

from collections import defaultdict

d = {'image1.jpg': ['UTSC', '2017-11-03','Happy Friday'], 'image2.jpg': ['UTSC', '2017-09-04','Happy Monday'], 'image3.jpg': ['UTSC', '2017-11-03','Happy Monday']}
newd = defaultdict(list)
for i in d:
    newd[d[i][1]].append(i)
print(dict(newd))

或没有收藏(由@antonvbr添加)

d = {'image1.jpg': ['UTSC', '2017-11-03','Happy Friday'], 'image2.jpg': ['UTSC', '2017-09-04','Happy Monday'], 'image3.jpg': ['UTSC', '2017-11-03','Happy Monday']}

newd = {}

# Loop over the dictionary d
for img, metadata in d.items():

    #Extract the date from 'metadata'
    date = metadata[1]

    # If key doesn't exist create an empty list
    if not newd.get(date):
        newd[date] = []

    # Add item to list inside dict
    newd[date].append(img)

print(newd)

输出:

{'2017-11-03': ['image1.jpg', 'image3.jpg'], '2017-09-04': ['image2.jpg']}

答案 2 :(得分:0)

    public static void main(String[] args) throws AWTException, IOException, URISyntaxException, Exception {

        NewClass n=NewClass.getInstance();
       Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            try {
                    saveHistory();//save send and recive traffic to file
                    System.out.println(1);

            } catch (IOException ex) {
                Logger.getLogger(BandWidthMeter.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }, "Shutdown-thread"));
   }    
}

     void saveHistory() throws IOException{
         Date date=new Date();
         SimpleDateFormat format=new SimpleDateFormat("yyyy/MM/dd hh:mm");
         String format1 = format.format(date);
         //convert traffic to kiloByte
         double session_Send=(double)send/1024;
          double session_Recive=(double)recive/1024;
         String row=format1+"-"+String.valueOf(session_Send)+"-"+String.valueOf(session_Recive);
        try (FileWriter fw = new FileWriter(new File("src/bandwidthmeter/history.txt"),true)) {
            fw.append(row);
            fw.append("\n");
        }
        try ( //update total.properties
                FileOutputStream out = new FileOutputStream("src/bandwidthmeter/total.properties")) {
            //convert traffic to megabyte
            double sessionSend=(double)send/1048576;
            double sessionRecive=(double)recive/1048576;
            totalSend+=sessionSend;
            totalRecive+=sessionRecive;
            prop.setProperty("totalSend",String.valueOf(totalSend));
            prop.setProperty("totalRecive",String.valueOf(totalRecive));
            prop.store(out,null);
            out.close();
        }
     }

答案 3 :(得分:0)

让我们首先通过一个例子来理解实际问题:

  

示例代码:

对于这些类型的列表问题,有一种模式:

假设你有一个清单:

a=[(2006,1),(2007,4),(2008,9),(2006,5)]

并且你希望将它转换为dict作为元组的第一个元素作为元组的键和第二个元素。类似的东西:

{2008: [9], 2006: [5], 2007: [4]}

但是有一个问题,你也想要那些具有不同值但键相同的键,如(2006,1)和(2006,5)键是相同的,但值是不同的。你希望那些值只附加一个键,所以预期输出:

{2008: [9], 2006: [1, 5], 2007: [4]}

对于这类问题,我们会这样做:

首先创建一个新的字典然后我们遵循这种模式:

if item[0] not in new_dict:
    new_dict[item[0]]=[item[1]]
else:
    new_dict[item[0]].append(item[1])

因此我们首先检查密钥是否在新的dict中,如果已经存在,则将duplicate key的值添加到其值中:

完整代码:

a=[(2006,1),(2007,4),(2008,9),(2006,5)]

new_dict={}

for item in a:
    if item[0] not in new_dict:
        new_dict[item[0]]=[item[1]]
    else:
        new_dict[item[0]].append(item[1])

print(new_dict)
  

现在您的解决方案没有任何外部模块:

d = {'image1.jpg': ['UTSC', '2017-11-03','Happy Friday'], 'image2.jpg': ['UTSC', '2017-09-04','Happy Monday'], 'image3.jpg': ['UTSC', '2017-11-03','Happy Monday']}
def create_date_dict(image_dict):
    date_dict={}
    for key,value in image_dict.items():
        if value[1] not in date_dict:
            date_dict[value[1]]=[key] #notice here carefully , we have to store key in list so we can append values to it in else part of condition we did `[key]` , not `key` 
        elif key not in date_dict[value[1]]:
            date_dict[value[1]].append(key)

    return date_dict

print(create_date_dict(d))

输出:

{'2017-09-04': ['image2.jpg'], '2017-11-03': ['image3.jpg', 'image1.jpg']}