开发者

For items in a dictonary, split the name of one item, add and remove some info python

开发者 https://www.devze.com 2023-03-27 16:08 出处:网络
I have a dictionary with this info: 开发者_运维百科 x = {Country:{City:Population},.....} but City name is now like: Country_City_Neighbourhood_Population (for some reason). I need to remove all th

I have a dictionary with this info:

开发者_运维百科
x = {Country:{City:Population},.....}

but City name is now like: Country_City_Neighbourhood_Population (for some reason). I need to remove all the information and just keep the City and Neighbourhood like this: CityNeighbourhood.

I did this:

for country in x:
 for city, pop in x[country].iteritems():
  isCountry = city.split("_").count("Ecuador")
  if isCountry > 0:
   city1 = city.split("_")
   city1.remove("Ecuador")
   city2 = city1[0:-1]
   city3 = ""
   for i in range(len(city2)-1):
    city3 = city3 + city2[i]

but I didn't obtain any reasonable result.


"".join(city.split("_")[1:-1])
  • city.split("_") gives a list of the words in "city" separated by "_".
  • [1:-1] slices the list to remove the first and last elements
  • "".join connects them back together, with the empty string in between


Try something like this:

for country in x:
    for city, pop in x[country].iteritems():
        if 'Ecuador' in city:
            print ''.join(city.split('_')[1:3])
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号