0

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.

agf
  • 171,228
  • 44
  • 289
  • 238
Alejandro
  • 4,945
  • 6
  • 32
  • 30

2 Answers2

4
"".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
Community
  • 1
  • 1
Katriel
  • 120,462
  • 19
  • 136
  • 170
  • thanks!!! but you mean that I have to do this: city3 = "".join(city.split("_")[1:-1]) ???? – Alejandro Aug 11 '11 at 14:22
  • @Alejandro: if you want... you can do whatever you like with the result of the call. Maybe you want `for country in x: x[country] = "".join(x[country].split("_")[1:-1])`? – Katriel Aug 11 '11 at 14:30
1

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])
Mike Graham
  • 73,987
  • 14
  • 101
  • 130
Fábio Diniz
  • 10,077
  • 3
  • 38
  • 45