需要帮助迭代python字典值

时间:2021-02-15 22:24:38

I'm working on a program to search through a dictionaries value set and perform a method on values that match a user input. I have to compare and sort these values.

我正在编写一个程序来搜索字典值集,并对与用户输入匹配的值执行方法。我必须比较和排序这些值。

This is the code I'm working with right now

这是我正在使用的代码

Code for value search and compare (very rough)

值搜索和比较代码(非常粗糙)

import nation
import pickle

KK = 1000000

pickle_in = open("nationsDict.dat","rb")
d = pickle.load(pickle_in)

k = raw_input("Enter a continent: ")

for value in d.values():
    if k in d.values()[0]:
        print d.values()[0]

Code for Nation class

*代码

class Nations:

    KK = 1000000

    def __init__(self, ctry, cont, pop, area):
        self.country = ctry
        self.continent = cont
        self.population = float(pop)
        self.area = float(area)

    def popDensity(self):
        popDensity = (self.population*self.KK) / self.area
        popDensity = str(round(popDensity, 2))
        return popDensity

Code for creating pickle dictionary

用于创建pickle字典的代码

import nation
import pickle


i=0
dictUN = {}

with open('UN.txt') as f:
    for line in f:

        """Data get from file"""
        elements = line.strip().split(",")

        n = nation.Nations(elements[0],elements[1],elements[2],elements[3])

        """Density"""
        n.popDensity()
        print "The density of", n.country, "is",n.popDensity(),"people per square mile."

        """Dictionary creation"""
        dictVal = (n.continent, n.population, n.area)
        dictUN.update({n.country: dictVal})


pickle_out = open("nationsDict.dat", "wb")
pickle.dump(dictUN, pickle_out)
pickle_out.close()

Here's a snippet from UN.txt

这是UN.txt的一个片段

Mauritania,Africa,3.5,397954
Mauritius,Africa,1.3,787
Mexico,North America,120.3,761606
Micronesia,Australia/Oceania,.11,271
Monaco,Europe,.031,0.76
*,Asia,3.0,603909
Montenegro,Europe,.65,5019
Morocco,Africa,33.0,172414

My problems at this point are pretty contained to the value search and compare. Specifically, my program has to

此时我的问题非常包含在值搜索和比较中。具体来说,我的程序必须

  1. Allow the user to search a continent (first element in value list)
  2. 允许用户搜索大陆(值列表中的第一个元素)

  3. Perform the method, Nations.popDensity (contained in nation class) on all matching countries
  4. 在所有匹配的国家/地区执行方法,Nations.popDensity(包含在国家/地区类别中)

  5. Compare the nations and return the top 5 density values per continent
  6. 比较各国并返回每个大陆的前5个密度值

I would say my one big question is how to handle the search of a dictionary by an element in a value. I've also considered about making a temp dictionary with the continent element as the key, but I'm not sure that would make my life any easier as I have to perform the popDensity method on it.

我想说我的一个大问题是如何通过值中的元素来处理字典的搜索。我还考虑过用大陆元素作为关键字制作临时词典,但我不确定这会让我的生活变得更轻松,因为我必须对它执行popDensity方法。

Any help is appreciated, Thanks!

任何帮助表示赞赏,谢谢!

2 个解决方案

#1


0  

  1. Initialize pandas series object
  2. 初始化pandas系列对象

  3. Iterate through the dictionary.
  4. 通过字典迭代。

  5. If the continent matches:

    如果大陆匹配:

    a. calculate the population density.

    一个。计算人口密度。

    b. if the value is larger than the smallest value in the pandas series:

    湾如果该值大于pandas系列中的最小值:

    i. remove the last entry

    一世。删除最后一个条目

    ii.append the value into the pandas series values and the country to the index

    ii。将值添加到pandas系列值中,将国家/地区添加到索引中

    iii. sort the pandas series object ascending = False

    III。排序pandas系列对象ascending = False

If you're going to do this repeatedly, then creating a continent->country dictionary definitely will save time.

如果你要反复这样做,那么创建一个大陆 - >国家字典肯定会节省时间。

#2


0  

Glad it was helpful. I'll add it as an answer, so you can accept it, if you like.

很高兴它很有帮助。我会将其添加为答案,如果您愿意,可以接受它。

Just as there is list comprehension, there is dictionary comprehension... It's pretty cool stuff! d2 = {k:d[k] for k in d.keys() if <some_elem> in d[k]} would give you a dict with a subset of the original dict that satisfies your requirements. You would have to fill in the <some_elem> in d[k] portion, because I haven't gone through all your code. You said that this is the main Q you have. Hopefully this gives you enough to solve it.

就像列表理解一样,有字典理解......这是非常酷的东西! d2 = {k:d [k]表示d.keys()中的k,如果d [k]}中的 会给你一个dict,其中包含满足你要求的原始字典的子集。您必须在d [k]部分填写 ,因为我没有完成所有代码。你说这是你的主要问题。希望这足以让你解决它。

#1


0  

  1. Initialize pandas series object
  2. 初始化pandas系列对象

  3. Iterate through the dictionary.
  4. 通过字典迭代。

  5. If the continent matches:

    如果大陆匹配:

    a. calculate the population density.

    一个。计算人口密度。

    b. if the value is larger than the smallest value in the pandas series:

    湾如果该值大于pandas系列中的最小值:

    i. remove the last entry

    一世。删除最后一个条目

    ii.append the value into the pandas series values and the country to the index

    ii。将值添加到pandas系列值中,将国家/地区添加到索引中

    iii. sort the pandas series object ascending = False

    III。排序pandas系列对象ascending = False

If you're going to do this repeatedly, then creating a continent->country dictionary definitely will save time.

如果你要反复这样做,那么创建一个大陆 - >国家字典肯定会节省时间。

#2


0  

Glad it was helpful. I'll add it as an answer, so you can accept it, if you like.

很高兴它很有帮助。我会将其添加为答案,如果您愿意,可以接受它。

Just as there is list comprehension, there is dictionary comprehension... It's pretty cool stuff! d2 = {k:d[k] for k in d.keys() if <some_elem> in d[k]} would give you a dict with a subset of the original dict that satisfies your requirements. You would have to fill in the <some_elem> in d[k] portion, because I haven't gone through all your code. You said that this is the main Q you have. Hopefully this gives you enough to solve it.

就像列表理解一样,有字典理解......这是非常酷的东西! d2 = {k:d [k]表示d.keys()中的k,如果d [k]}中的 会给你一个dict,其中包含满足你要求的原始字典的子集。您必须在d [k]部分填写 ,因为我没有完成所有代码。你说这是你的主要问题。希望这足以让你解决它。