如何将字典的字符串值转换为布尔值?

时间:2018-10-02 14:23:06

标签: python dictionary boolean key-value-store

我创建了一个包含键和值的字典。读完这样的文本文件后:

test1
    House: True
    Car: False
    Money: False
    Case: 1

test2
    House: True
    Car: False
    Money: False
    Case: 2

test3
    House: True
    Car: False
    Money: False
    Case: 3

创建字典。问题在于这些值被读取为字符串。我需要将它们作为布尔值,以便以后可以将它们解析为JSON文件并将其用作布尔值。创建的字典称为answer。我尝试了以下操作,但这只是给我True作为布尔值:

    to_json = {}
    block_cnt = 1
    header = re.compile('[a-zA-Z0-9]')
    inner = re.compile("[\t]")
    empty = re.compile("[\n]",)`

    with open(rDEMO_parameters.txt', 'r') as document:
    for line in document:
        #print line
        if empty.match(line[0]):
            continue

        elif header.match(line[0]):
            if answer:
                to_json[block_cnt] = answer
                #print answer
                block_cnt += 1
                answer = {}
        elif inner.match(line[0]):
            _key, value = line.split(":  ")
            tab, key = _key.split("\t")
            answer[key] = value.split()
           for key in answer.keys():
            if key == "House":
                answer[key] = map(bool, answer[key])
            if key == "Car":
                answer[key] = map(bool, answer[key])
            if key == "Money":
                answer[key] = map(bool, answer[key])
            if key == "Case":
                answer[key] = map(int, answer[key])


   f = open(r"parameters.json", "w")

   json.dump(to_json, f)
   f.close()

然后在转换之后,我只会得到类似这样的信息,但所有内容都只能在一行中显示出来:

 {1
   {
    House: True
    Car: True
    Money: True
    Case: [1]
             } }
 {2
   {
    House: True
    Car: True
    Money: True
    Case: [2] } }
 {3
    {
    House: True
    Car: True
    Money: True
    Case: [3] }}

因此所有字符串都转换为True布尔值,事实并非如此。 另一个问题是在列表中读取值。有什么方法可以避免这种情况?谢谢。

4 个答案:

答案 0 :(得分:4)

package com.example.qdogg.mealmapnb; //@Author Quinn Clark 2018 // /** *Sorting based on proximity soon */ import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public abstract class SleepMap extends MainActivity implements OnItemClickListener, LocationProviderSleepMap.LocationProviderListener { ListView listView; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sleep_map); listView = (ListView) findViewById(R.id.sleeplist); listView.setOnItemClickListener(this); } @Override public void gotCurrentLocation(Location location) { final Location CLSM = new Location(""); CLSM.setLatitude(location.getLatitude()); CLSM.setLongitude(location.getLongitude()); Location IFCSM = new Location(""); IFCSM.setLatitude(51.042580); IFCSM.setLongitude(-114.062782); Location BGCSM = new Location(""); BGCSM.setLatitude(51.039370); BGCSM.setLongitude(-114.084020); float CLSMtoIFCSM = CLSM.distanceTo(IFCSM); float CLSMtoBGC = CLSM.distanceTo(BGCSM); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: Intent innfromthecold = new Intent(this, ifcactivity.class); startActivity(innfromthecold); break; case 1: Intent boysandgirlsclub = new Intent(this, bgcactivity.class); startActivity(boysandgirlsclub); break; default: //Nothing } } } 用于将函数应用于可迭代的每个值。

您可以改用ast.literal_eval

map

此外,您无需在单独的from ast import literal_eval answer[key] = literal_eval(answer[key]) 语句中检查每个键。如果您在逻辑中同时使用键和值,则遍历if也是更惯用的:

dict.items

最后,考虑使用字典理解:

for key, value in answer.items():
    if key in ('House', 'Car', 'Money'):
        answer[key] = literal_eval(value)

答案 1 :(得分:2)

map(bool, answer[key])正在将函数映射到字符串的字符上。所有非空字符均为true,因此您应该只希望获得True。

您需要实际检查== "True"

换句话说,bool("False")的结果可能会让您惊讶

答案 2 :(得分:1)

如果我了解您的布尔词是字符串,并且您实际上需要它们是布尔词,那么字典理解会起作用

d = {k: True if d[k] == 'True' else False for k in d}
 {'House': True, 'Car': False, 'Money': False}

答案 3 :(得分:0)

为什么不简单:

for key in answer.keys():
   answer[key] = answer[key] == "True"