![](/img/trans.png)
[英]Replace a key in one dictionary with the value of the key from another dictionary in Python
[英]Extracting a key from a dictionary to another dictionary in Python
我有一個很大的python字典。 其鍵之一具有另一個字典作為值。 我想使用這些值創建一個新詞典,然后從原始詞典中刪除鍵。
有什么功能可以將值導出到另一個字典中? 要刪除,我知道我可以使用.pop()
函數。 我嘗試使用谷歌搜索,但未成功。
這是字典。 我用星星來屏蔽敏感信息。 我需要的密鑰是billing_address
,它具有另一個字典作為值:
{
'shipping_cost_tax': '0.0000',
'refunded_amount': '0.0000',
'external_source': None,
'discount_amount': '0.0000',
'base_wrapping_cost': '0.0000',
'shipping_cost_tax_class_id': 2,
'payment_method': 'PayPal',
'handling_cost_ex_tax': '0.0000',
'store_credit_amount': '0.0000',
'shipping_cost_inc_tax': '11.0000',
'handling_cost_tax_class_id': 2,
'currency_id': 1,
'payment_status': 'captured',
'subtotal_ex_tax': '99.0000',
'total_inc_tax': '11.0000',
'handling_cost_inc_tax': '0.0000',
'total_ex_tax': '11.0000',
'is_deleted': False,
'status_id': 5,
'id': 614534,
'shipping_cost_ex_tax': '11.0000',
'date_shipped': '',
'order_source': 'www',
'status': 'Cancelled',
'handling_cost_tax': '0.0000',
'items_total': 3,
'wrapping_cost_tax': '0.0000',
'date_created': 'Wed,
09 Jul 2014 12:22:17 +0000',
'total_tax': '0.0000',
'order_is_digital': False,
'date_modified': 'Thu,
30 Oct 2014 02:34:07 +0000',
'geoip_country': 'Australia',
'base_shipping_cost': '11.0000',
'payment_provider_id': '**************',
'staff_notes': '',
'default_currency_id': 1,
'currency_code': 'AUD',
'currency_exchange_rate': '1.0000000000',
'coupon_discount': '99.0000',
'customer_message': '',
'subtotal_inc_tax': '99.0000',
'gift_certificate_amount': '0.0000',
'items_shipped': 0,
'default_currency_code': 'AUD',
'customer_id': 1,
'geoip_country_iso2': 'AU',
'ip_address': '124.168.160.136',
'shipping_address_count': 1,
'wrapping_cost_ex_tax': '0.0000',
'base_handling_cost': '0.0000',
'wrapping_cost_tax_class_id': 3,
'ebay_order_id': '0',
'wrapping_cost_inc_tax': '0.0000',
'billing_address': {
'state': '*******',
'street_1': '*************',
'street_2': '',
'country_iso2': 'AU',
'last_name': '************',
'company': '***************',
'country': 'Australia',
'first_name': '*********',
'email': '***************',
'phone': '*************',
'city': '*************',
'zip': '************'
},
'subtotal_tax': '0.0000'
}
編輯:
def popAndMergeDicts(line):
tempDict = line['billing_address']
del line['billing_address']
for i in tempDict:
line[i] = tempDict[i]
print(line)
def process_file(filename):
lines = tuple(open(filename))
for line in lines[0:1]:
popAndMergeDicts(line)
process_file('allOrdersData')
allOrdersData是一個文件,其中有很多字典,就像我之前發布的字典一樣,每行一個。 嘗試運行它時出現以下錯誤:
TypeError:字符串索引必須是整數
編輯2:
沒關系,可以在ast.literal_eval中使用它:
import ast
def popAndMergeDicts(line):
dictLine = ast.literal_eval(line)
tempDict = dictLine['billing_address']
del dictLine['billing_address']
for i in tempDict:
dictLine[i] = tempDict[i]
print(dictLine)
def process_file(filename):
lines = tuple(open(filename))
for line in lines[0:]:
popAndMergeDicts(line)
process_file('allOrdersData')
只需使用.pop()
:它返回彈出的值。 例如,
#!/usr/bin/env python
import pprint
big_dict = {
'shipping_cost_tax': '0.0000',
'refunded_amount': '0.0000',
#etc
'billing_address': {
'state': '*******',
'street_1': '*************',
'street_2': '',
'country_iso2': 'AU',
#etc
},
'subtotal_tax': '0.0000'
}
print 'Before'
pprint.pprint(big_dict, indent=4)
bill_dict = big_dict.pop('billing_address')
print '\nBill dict'
pprint.pprint(bill_dict, indent=4)
print '\nAfter'
pprint.pprint(big_dict, indent=4)
輸出
Before
{ 'billing_address': { 'country_iso2': 'AU',
'state': '*******',
'street_1': '*************',
'street_2': ''},
'refunded_amount': '0.0000',
'shipping_cost_tax': '0.0000',
'subtotal_tax': '0.0000'}
Bill dict
{ 'country_iso2': 'AU',
'state': '*******',
'street_1': '*************',
'street_2': ''}
After
{ 'refunded_amount': '0.0000',
'shipping_cost_tax': '0.0000',
'subtotal_tax': '0.0000'}
要將鍵/值保留在原始詞典中,而不是創建一個新的鍵/值,您可以執行Marichyasana建議的操作:
bill_dict = big_dict.pop('billing_address')
for k in bill_dict:
big_dict[k] = bill_dict[k]
del bill_dict
print '\nAfter'
pprint.pprint(big_dict, indent=4)
輸出
After
{ 'country_iso2': 'AU',
'refunded_amount': '0.0000',
'shipping_cost_tax': '0.0000',
'state': '*******',
'street_1': '*************',
'street_2': '',
'subtotal_tax': '0.0000'}
我還刪除了臨時bill_dict
。 這不是嚴格必要的,因為bill_dict
一旦超出范圍就會自動刪除。
如果您只想引用 “子詞典”,則可以簡單地使用(其中d
是您的原始詞典):
billing1 = d['billing_address']
如果您需要單獨的副本,則可以使用以下任何一種方法:
billing2 = dict(d['billing_address'])
billing3 = d['billing_address'].copy()
billing4 = copy.copy(d['billing_address']) # after import copy
對billing1
值的billing1
將反映在您的原始詞典中。 其他三個值的更改將不會反映在原始詞典中。
如果您還想刪除billing_address
鍵(例如您在問題中建議但在評論中回billing_address
),則首先使用上述方法之一,然后使用:
del d['billing_address']
或者,作為第一步,如果您承諾從原始字典中刪除密鑰,請使用dict.pop()
billing5 = d.pop('billing_address')
假設“ a”為字典的名稱
令'b'為billing_address詞典的名稱
b=a['billing_address']
del a['billing_address']
for i in b:
a[i]=b[i]
ans = {key:val for key, val in input_dict.pop('billing_address').items()}
dict1 = {'shipping_cost_tax': '0.0000', 'refunded_amount': '0.0000', 'external_source': None, 'discount_amount': '0.0000', 'base_wrapping_cost': '0.0000', 'shipping_cost_tax_class_id': 2, 'payment_method': 'PayPal', 'handling_cost_ex_tax': '0.0000', 'store_credit_amount': '0.0000', 'shipping_cost_inc_tax': '11.0000', 'handling_cost_tax_class_id': 2, 'currency_id': 1, 'payment_status': 'captured', 'subtotal_ex_tax': '99.0000', 'total_inc_tax': '11.0000', 'handling_cost_inc_tax': '0.0000', 'total_ex_tax': '11.0000', 'is_deleted': False, 'status_id': 5, 'id': 614534, 'shipping_cost_ex_tax': '11.0000', 'date_shipped': '', 'order_source': 'www', 'status': 'Cancelled', 'handling_cost_tax': '0.0000', 'items_total': 3, 'wrapping_cost_tax': '0.0000', 'date_created': 'Wed, 09 Jul 2014 12:22:17 +0000', 'total_tax': '0.0000', 'order_is_digital': False, 'date_modified': 'Thu, 30 Oct 2014 02:34:07 +0000', 'geoip_country': 'Australia', 'base_shipping_cost': '11.0000', 'payment_provider_id': '**************', 'staff_notes': '', 'default_currency_id': 1, 'currency_code': 'AUD', 'currency_exchange_rate': '1.0000000000', 'coupon_discount': '99.0000', 'customer_message': '', 'subtotal_inc_tax': '99.0000', 'gift_certificate_amount': '0.0000', 'items_shipped': 0, 'default_currency_code': 'AUD', 'customer_id': 1, 'geoip_country_iso2': 'AU', 'ip_address': '124.168.160.136', 'shipping_address_count': 1, 'wrapping_cost_ex_tax': '0.0000', 'base_handling_cost': '0.0000', 'wrapping_cost_tax_class_id': 3, 'ebay_order_id': '0', 'wrapping_cost_inc_tax': '0.0000', 'billing_address': {'state': '*******', 'street_1': '*************', 'street_2': '', 'country_iso2': 'AU', 'last_name': '************', 'company': '***************', 'country': 'Australia', 'first_name': '*********', 'email': '***************', 'phone': '*************', 'city': '*************', 'zip': '************'}, 'subtotal_tax': '0.0000'}
print {'billing_address': dict1['billing_address']}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.