首页 \ 问答 \ 格式化字符串中的python dict [复制](python dict in formatted string [duplicate])

格式化字符串中的python dict [复制](python dict in formatted string [duplicate])

这个问题在这里已经有了答案:

我想在字符串中写一个python字典。 项目的值应由格式化的字符串给出。

我期望以下工作,但它不会,因为用于定义dict的第一个'{'被解释为格式化字段

In: "{'key_1': '{value}'}".format(**{'value': 'test'})

以下工作正常,但不返回预期的字典:

In: "'key_1': '{value}'".format(**{'value': 'test'})
Out: "'key_1': 'test'"

克服这个问题的一种方法是使用list brakets并稍后用dict brakets替换它们:

In: "['key_1': '{value}']".format(**{'value': 'test'}).replace('[', '{').replace(']', '}')
Out: "{'key_1': 'test'}"

如何以更好的方式写这个?


I want to write a python dictionary in a string. The values of the items should be give by the formatted string.

I expected the following to work, but it doesnt because the first '{' used to define the dict is interpreted as a formated field

In: "{'key_1': '{value}'}".format(**{'value': 'test'})

the following works fine, but doesn't return the expected dict:

In: "'key_1': '{value}'".format(**{'value': 'test'})
Out: "'key_1': 'test'"

one way to overcome the problem is by using list brakets and replace them later by the dict brakets:

In: "['key_1': '{value}']".format(**{'value': 'test'}).replace('[', '{').replace(']', '}')
Out: "{'key_1': 'test'}"

How to write this in a better way?


原文:https://stackoverflow.com/questions/30394912
更新时间:2021-12-21 06:12

最满意答案

Base类引用分配给Derived类引用变量是非法的。

X类型的变量只能是对X类型或派生类型的对象的引用。

您可能需要另一个包含与现有对象相同数据的SpecialContact实例。 没有办法避免手动复制。

当我需要将匹配属性从一个对象复制到另一个不兼容的对象时,我使用以下扩展方法(1):

public static void AssignFrom(this object destination, object source) {
  Type dest_type = destination.GetType();
  Type source_type = source.GetType();

  var matching_props = from d in dest_type.GetProperties()
                        join s in source_type.GetProperties()
                        on d.Name equals s.Name
                        where d.IsWritable() && s.IsReadable()
                        select new {
                          source = s,
                          destination = d
                        };

  foreach (var prop in matching_props) {
    prop.destination.SetValue(destination, prop.source.GetValue(source, null), null);
  }
}

那你可以这样做:

specialContact.assignFrom(contact);

请考虑这个解决方法。 正确的解决方案是正确设计您的类层次结构,而您不会遇到此问题。


1注意:它按名称匹配属性并假定它们属于同一类型。


It is illegal to assign Base class reference to the Derived class reference variable.

Variable of type X can only be a reference to an object of type X or derived.

You probably need to have another instance of SpecialContact which contains the same data as existing object. There is no way to avoid manual copying.

I use the following extension method when I need to copy the matching properties from one object to another incompatible one(1):

public static void AssignFrom(this object destination, object source) {
  Type dest_type = destination.GetType();
  Type source_type = source.GetType();

  var matching_props = from d in dest_type.GetProperties()
                        join s in source_type.GetProperties()
                        on d.Name equals s.Name
                        where d.IsWritable() && s.IsReadable()
                        select new {
                          source = s,
                          destination = d
                        };

  foreach (var prop in matching_props) {
    prop.destination.SetValue(destination, prop.source.GetValue(source, null), null);
  }
}

Then you can do:

specialContact.assignFrom(contact);

Please consider this a workaround. The proper solution would be to design properly your class hierarchy where you do not come to this problem.


1 Note: it matches the properties by name and assumes they are of the same type.

相关问答

更多
  • 不,没有内置的方式来转换类似你说的话。 最简单的方法就是做你所建议的:创建一个DerivedClass(BaseClass)构造函数。 其他选项基本上可以自动化从基础到派生实例的属性复制,例如使用反射。 您发布的代码将会编译,因为我确信你已经看到了,但是当您运行它时会抛出一个空引用异常,因为由于myBaseObject as DerivedClass将会为null ,因为它不是DerivedClass的一个实例。 No, there's no built-in way to convert a class ...
  • StopsVisited不是Stops的子类型; 它是Stops的一个子类型,这是完全不同的东西。 我同意duffymo的观点:子类型是对你的问题的错误方法,但是你提到的特定功能在C#4中被称为“协方差”或“输出安全”; 你可以在这里阅读。 StopsVisited is not a subtype of Stops; it's a subtype of Stops, which is an entirely different t ...
  • 如果您可以更改创建代码,那么您可能会忽略这一点: template void deleter(void* p){ delete static_cast(p); } template class Container{ private: T* obj; typedef void (*deleter_func)(void*); deleter_func obj_deleter; public: Container(T* o, deleter_fu ...
  • p是Parent的实例,因此您无法告诉运行时将其解释为一个。 编译器没有捕获它,因为这样的代码 Parent p = new Child(); Child c = (Child)p; 并且编译器不进行捕获它所需的静态代码分析。 不检查的原因是: 这很费时间 它只能捕获一些错误实例。 p is an instance of Parent, so you cannot tell the runtime to interpret it as one. The compiler does not catch ...
  • 将Base类引用分配给Derived类引用变量是非法的。 X类型的变量只能是对X类型或派生类型的对象的引用。 您可能需要另一个包含与现有对象相同数据的SpecialContact实例。 没有办法避免手动复制。 当我需要将匹配属性从一个对象复制到另一个不兼容的对象时,我使用以下扩展方法(1): public static void AssignFrom(this object destination, object source) { Type dest_type = destination.GetTyp ...
  • 在创建对象后,无法更改对象的类型(构造和销毁除外,派生类对象暂时变为基类对象)。 由于派生类对象可能比它们的基类大,因此也无法使用它。 创建新派生对象,重置指针然后销毁基础对象的方法是有效的,如果没有其他人持有另一个指向基类的指针。 如果有任何其他指针或对原始对象的引用,它将在之后悬空。 但是如果你控制了该类的唯一指针/引用(例如,如果你只通过一个从不泄漏指针或对真实对象的引用的单例代理对象来访问它),那么这个方法是有效的。 There is no way to change the type of an ...
  • 我错过了什么以及将派生类的列表转换为其基类列表的正确方法是什么? 该列表仍包含DerivedClass实例,但它们被用作对BaseClass引用。 但是,此API的任何使用者都不会知道这一点,所以他们会将此视为BaseClass元素。 这是常见的,通常是正确的方法。 如果您需要实际将实例转换为BaseClass实例(这可能不是必需的),您需要从DerivedClass成员实际制作新的BaseClass实例,即: List _baseClass = _derivedClass.Selec ...
  • 编辑:我已经增加了示例以使它们更清晰。 在演员阵容上传递通常是糟糕设计的标志。 演员有自己的位置,但这看起来并不像。 您需要问自己,您想对cBodyParts存储的对象做什么。 当然,你会Hand或Head做不同的事情,但你可能会以某种方式抽象它们:这就是虚函数的作用。 因此,除了您已经为类编写的内容之外,您还需要一个额外的虚函数: class BodyPart { // Same as you wrote, plus: public: virtual void InitialisePart() = ...
  • 如果您有派生类,则需要在数据协定上“宣传”这些类: [DataContract] [KnownType(typeof(DerivedType1))] [KnownType(typeof(DerivedType2))] public class BaseType { ...... } 或者您也可以在服务合同上指定这种关系: [ServiceKnownType(typeof(DerivedType1))] [ServiceKnownType(typeof(DerivedType2))] [Ser ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)