将字典转换为字符串

时间:2015-07-31 10:53:59

标签: python python-2.7 dictionary

我在将字典转换为python中的字符串时遇到问题。我试图从我的一个变量中提取信息,但似乎无法删除信息周围的方括号

Period period = new Period(d1, d2);
System.out.print(period.getYears() + " years, ");
System.out.print(period.getMonths() + " months, ");

有没有办法删除方括号,还是我必须找到另一种方法从字典中取出信息?

编辑:

更详细地说,我在这里尝试做的是以下

for line in str(object):
    if line.startswith ('['):
        new_object = object.replace('[', '')

我希望这能使我想做的更清楚

2 个答案:

答案 0 :(得分:3)

info.json()返回的对象是Python字典,因此您可以使用普通的Python语法访问其内容。我承认它可能会有点棘手,因为JSON字典通常包含其他字典和列表,但是如果以格式良好的方式打印JSON对象,通常不太难以弄清楚是什么。最简单的方法是使用标准Python dumps()模块中的json函数。

下面的代码将JSON数据检索到名为data的字典中 然后,它会在data的'weather'项目列表中打印'description'字符串 然后它将所有数据(只是'weather'项目)保存为ASCII编码的JSON文件。
然后它再次将JSON数据读回到一个名为newdata的新dict中,然后将其打印出来。 最后,它再次打印天气描述,以验证我们收回了之前看到的内容。 :)

import requests, json

#The base URL of the weather service
endpoint = 'http://api.openweathermap.org/data/2.5/weather'

#Filename for saving JSON data to
fname = 'data.json'

city = 'dublin'
country = 'ireland'

params = {
    'q': '%s,%s' % (city, country), 
    'mode': 'json',
}

#Fetch the info
info = requests.get(endpoint, params=params)
data = info.json()
#print json.dumps(data, indent=4)

#Extract the value of 'description' from the list in 'weather'
print '\ndescription: %s\n' % data['weather'][0]['description']

#Save data
with open(fname, 'w') as f:
    json.dump(data, f, indent=4)

#Reload data
with open(fname, 'r') as f:
    newdata = json.load(f)

#Show all the data we just read in
print json.dumps(newdata, indent=4)

print '\ndescription: %s\n' % data['weather'][0]['description']

<强>输出

description: light intensity shower rain

{
    "clouds": {
        "all": 75
    }, 
    "name": "Dublin", 
    "visibility": 10000, 
    "sys": {
        "country": "IE", 
        "sunset": 1438374108, 
        "message": 0.0118, 
        "type": 1, 
        "id": 5237, 
        "sunrise": 1438317600
    }, 
    "weather": [
        {
            "description": "light intensity shower rain", 
            "main": "Rain", 
            "id": 520, 
            "icon": "09d"
        }
    ], 
    "coord": {
        "lat": 53.340000000000003, 
        "lon": -6.2699999999999996
    }, 
    "base": "stations", 
    "dt": 1438347600, 
    "main": {
        "pressure": 1014, 
        "humidity": 62, 
        "temp_max": 288.14999999999998, 
        "temp": 288.14999999999998, 
        "temp_min": 288.14999999999998
    }, 
    "id": 2964574, 
    "wind": {
        "speed": 8.1999999999999993, 
        "deg": 210
    }, 
    "cod": 200
}

description: light intensity shower rain

答案 1 :(得分:1)

我不太确定你在这里尝试做什么(没有看到你的字典),但如果你有一个像x = "[myString]"这样的字符串,你可以做以下事情:

x = x.replace("[", "").replace("]", "")

如果这不起作用,您很可能实际获得了返回的列表。虽然如果是这种情况,你应该看到这样的错误:

>>> x = [1,2,3]
>>> x.replace("[", "")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'replace'

修改1:

我认为你对这里的回归存在误解。如果您只是在寻找带有api天气的csv输出文件,请尝试以下方法:

import requests
import csv

city = 'dublin'
country = 'ireland'

info = requests.get('http://api.openweathermap.org/data/2.5/weather?q='+city +','+ country +'&mode=json')

weather = info.json()['weather']
weather_fieldnames = ["id", "main", "description", "icon"]

with open('city.txt', 'w') as f:
  csvwriter = csv.DictWriter(f, fieldnames=weather_fieldnames)
  for w in weather:
    csvwriter.writerow(w)

这是通过循环遍历您正在获取的项目列表并使用csv.DictWriter将其作为csv文件中的行写入来实现的。

<强>加成

不要打电话给你的字典object - 这是核心语言的保留字。